c# - WPF 将控件动态添加到 UserControl 的特定区域
问题描述
下午好,
我似乎对 WPF 有一个简单的问题。
在谷歌搜索了几个小时后,我找不到任何与我正在寻找的东西相似的东西。
简而言之,我正在寻找一种方法来在我的自定义 UserControl 中定义一个区域,如下所示:
<UserControl>
<TemplateArea x:Name="FormControls">
</TemplateArea>
</UserControl>
然后在使用我的自定义控件的 Window、Panel 等中执行此操作:
<TheUserControl>
<TemplateArea x:Name="FormControls">
<TextBox/>
</TemplateArea>
</TheUserControl>
.. 结果,TextBox 将直接粘贴到我的自定义控件中。
解决方案
一种解决方案是创建一个包含控件数组的依赖项属性,并在控件内部将其绑定到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>
推荐阅读
- c++ - OpenCV 当时未能创建多个跟踪器
- python - 在字典中定义函数
- methods - 打印所有 Prime、Sophie Germain Prime、Twin Prime 和 Mersenne Prime 数字 1 到 1000000 的代码
- python-3.x - 在地址中搜索数字和字母数字邮政编码
- python - 如何让 python 启动命令提示符会话并在其中运行命令?
- php - 登录后错误 419 页面过期 - Laravel - Windows server 2012 R2
- javascript - 关于react redux的问题
- javascript - 如何在悬停在不同文本上时多次更改图像
- excel - 如何将 x 个 0 添加到 COUNTIF MAX VLOOKUP 公式的结果
- python - 获取查询 sqlalchemy 中所有值的属性