首页 > 解决方案 > WPF 将控件动态添加到 UserControl 的特定区域

问题描述

下午好,

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

在谷歌搜索了几个小时后,我找不到任何与我正在寻找的东西相似的东西。

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

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

    </TemplateArea>
</UserControl>

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

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

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

标签: c#wpf

解决方案


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

孩子.xaml

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

孩子.cs

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

主机.xaml

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

推荐阅读