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

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

问题描述

我正在尝试创建一个具有两行 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 - 在用户控件中托管内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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