WPF将控件动态添加到UserControl的特定区域

时间:2018-11-22 18:11:42

标签: c# wpf

下午好,

我似乎对WPF有一个简单的问题。

在搜索了好几个小时后,我找不到与我想要的东西相似的东西。

简单来说,我正在寻找一种在我的自定义UserControl中定义区域的方法,如下所示:

<UserControl>
    <TemplateArea x:Name="FormControls">

    </TemplateArea>
</UserControl>

然后在使用我的自定义控件的Window,Panel等内部执行此操作:

<TheUserControl>
    <TemplateArea x:Name="FormControls">
        <TextBox/>
    </TemplateArea>
</TheUserControl>

..因此,TextBox将直接粘贴到我的自定义控件中。

1 个答案:

答案 0 :(得分:0)

一种解决方案是创建一个包含一系列控件的依赖项属性,然后在控件内部将其绑定到ItemsControl

child.xaml

<UserControl x:Name="RootControl">
  <...>   <!-- your other UI -->
    <ItemsControl ItemSource="{Binding Items, ElementName=RootControl}" /> 
    <!-- style the items and/or panel as you wish -->
  </...>
</UserControl>

child.cs

public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register(
    "Items", typeof(Observable<UIElement>), typeof(Child),
    new PropertyMetadata(new Observable<UIElement>()));

host.xaml

<Page>
  <...>
    <my:Child>
      <my:Child.Items>
        <TextBox/>
        <CheckBox/>
      </my:Child.Items>
    </my:Child>
  </...>
</Page>