且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF - 在 UserControl 中托管内容

更新时间:2023-12-06 14:04:46

以下代码

<local:UserControl1>
    <Button>Click me</Button>
</local:UserControl1>

表示您将 UserControl1 的 Content 属性设置为该按钮.这个按钮只是替换了 UserControls1 的标记.因此,您在 UserControl1.xaml 中拥有的所有内容都不再存在.

Means that you set UserControl1's Content property to be that button. This button simply replaces that UserControls1's markup. So all the things that you have in UserControl1.xaml are not there any more.

编辑

如果您希望您的 UserControl 托管一些将在其外部某处设置的标记,您可以向其添加一个 DependencyProperty,例如:

If you want your UserControl to host some markup that will be set somewhere outside of it, you can add a DependencyProperty to it, for example:

    /// <summary>
    /// Gets or sets additional content for the UserControl
    /// </summary>
    public object AdditionalContent
    {
        get { return (object)GetValue(AdditionalContentProperty); }
        set { SetValue(AdditionalContentProperty, value); }
    }
    public static readonly DependencyProperty AdditionalContentProperty =
        DependencyProperty.Register("AdditionalContent", typeof(object), typeof(UserControl1),
          new PropertyMetadata(null));

并在其标记中添加一些元素以托管该附加内容.以下是扩展您提供的标记的示例:

And add some element to it's markup to host that additional content. Here's an example extending the markup you provided:

<UserControl ... Name="userControl">
    <Grid Background="LightBlue">
        <Grid.RowDefinitions>
            <RowDefinition Height="50" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <TextBlock Text="Title" FontSize="30" Margin="10,0,0,0"/>
        <ContentPresenter Content="{Binding AdditionalContent, ElementName=userControl}" />
    </Grid>
</UserControl>

现在您可以按如下方式使用它:

Now you can use it as following:

<local:UserControl1>
    <local:UserControl1.AdditionalContent>
        <Button>Click me</Button>
    </local:UserControl1.AdditionalContent>
</local:UserControl1>