WPF - 在 UserControl 中托管内容 [英] WPF - Hosting content inside a UserControl

查看:22
本文介绍了WPF - 在 UserControl 中托管内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个具有两行 Grid 的用户控件.第一行用于标题,第二行用于将在用户控件之外定义的内容,例如我们示例中的 Button.

I'm trying to create a user control that has a Grid with two rows. the first row for a title and the second one for a content that will be defined outside the user control such as a Button in our example.

不知何故,我没有让它发挥作用.

Somehow I didn't get it to work.

UserControl1 xaml:

UserControl1 xaml:

  <Grid Background="LightBlue">
    <Grid.RowDefinitions>
        <RowDefinition Height="50" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <TextBlock Text="Title" FontSize="30" Margin="10,0,0,0"/>
</Grid>

主窗口 xaml:

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

下面的图片应该可以解释我的问题:

The picture below should explain what's my problem:

推荐答案

以下代码

<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>

这篇关于WPF - 在 UserControl 中托管内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆