简体   繁体   中英

WPF add element to user control via DependencyProperty

i try add controls via DependencyProperty, first have this user control:

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

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

To expand on Clemen's comment, you don't need that Grid DP. Just do this in your UserControl instead:

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

And then in your parent class add the content directly:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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