简体   繁体   English

WPF 通过 DependencyProperty 向用户控件添加元素

[英]WPF add element to user control via DependencyProperty

i try add controls via DependencyProperty, first have this user control:我尝试通过 DependencyProperty 添加控件,首先拥有此用户控件:

<UserControl x:Class="Project.Common.Controls.SaveFromSource" ...>
    <Grid x:Name="grid">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Grid Grid.Row="0"/>
    </Grid>
</UserControl>

In code behing has this:在代码行为中有这样的:

namespace Project.Common.Controls
{
    public partial class SaveFromSource : UserControl
    {
        public static readonly DependencyProperty GridProperty = DependencyProperty.Register("Grid", typeof(Grid), typeof(FilterFromSource));

        public Grid Grid
        {
            get { return (Grid)GetValue(GridProperty); }
            set { SetValue(GridProperty, value); }
        }

        public SaveFromSource()
        {
            InitializeComponent();

            if (this.Grid != null)
            {
                this.grid = this.Grid;
            }
        }
    }
}

And in new window have this:在新的 window 中有这个:

<controls:SaveFromSource>
    <controls:SaveFromSource.Grid>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="auto"/>
            </Grid.RowDefinitions>

            <TextBox Grid.Row="0" Text="CONTROL 1"/>
            <TextBox Grid.Row="1" Text="CONTROL 2"/>
        </Grid>
    </controls:SaveFromSource.Grid>
</controls:SaveFromSource>

The question is, why textbox's dont show in user control?问题是,为什么文本框不显示在用户控件中?

** I need to dynamically add controls to the user control in order to reuse code. ** 我需要向用户控件动态添加控件以便重用代码。

Thanks for help.感谢帮助。

Welcome to SO!欢迎来到 SO!

To expand on Clemen's comment, you don't need that Grid DP.要扩展 Clemen 的评论,您不需要那个 Grid DP。 Just do this in your UserControl instead:只需在您的 UserControl 中执行此操作:

<!--<Grid Grid.Row="0"/>    <--- get rid of this        -->
<ContentPresenter Grid.Row="0" />

And then in your parent class add the content directly:然后在你的父 class 中直接添加内容:

<controls:SaveFromSource>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>

        <TextBox Grid.Row="0" Text="CONTROL 1"/>
        <TextBox Grid.Row="1" Text="CONTROL 2"/>
    </Grid>
</controls:SaveFromSource>

If your reason for doing this is that you need more than one content then you'll have to add additional DPs for that to your UserControl and bind to it in your XAML with ContentControls.如果您这样做的原因是您需要多个内容,那么您必须为此添加额外的 DP 到您的 UserControl 并在您的 XAML 中使用 ContentControls 绑定到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM