簡體   English   中英

WPF 通過 DependencyProperty 向用戶控件添加元素

[英]WPF add element to user control via DependencyProperty

我嘗試通過 DependencyProperty 添加控件,首先擁有此用戶控件:

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

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

在代碼行為中有這樣的:

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

在新的 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>

問題是,為什么文本框不顯示在用戶控件中?

** 我需要向用戶控件動態添加控件以便重用代碼。

感謝幫助。

歡迎來到 SO!

要擴展 Clemen 的評論,您不需要那個 Grid DP。 只需在您的 UserControl 中執行此操作:

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

然后在你的父 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>

如果您這樣做的原因是您需要多個內容,那么您必須為此添加額外的 DP 到您的 UserControl 並在您的 XAML 中使用 ContentControls 綁定到它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM