c# - WPF ItemsControl 绑定到 UserControls
问题描述
ItemsControl
绑定到对象集合可以UserControl
正常工作。但是,我想应用其他 XAML,例如 aBorder
等。
但是,不是Border
使用 UserControl,而是仅呈现 UserControl 本身。<ItemsControl.ItemTemplate>
似乎没有任何效果。
问题:如何设计带有附加 XAML 的 ItemTemplate?目前,这个标签似乎被“忽略”了。
视图模型:ObservableCollection<UserControl> MyUserControls
<ItemsControl ItemsSource="{Binding MyUserControls, lementName=popupContainer}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border ...>
<ContentControl Content="{Binding}" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
解决方案
查看参考源会发现IsItemItsOwnContainerOverride
ItemsControl 类的方法具有以下实现:
protected virtual bool IsItemItsOwnContainerOverride(object item)
{
return (item is UIElement);
}
因此,如果您将 UIElements 集合传递给 ItemsControl 的 ItemsSource,这些元素将直接用作项目容器,而无需通常将ContentPresenter
. 因此根本没有ItemTemplate
应用。
所以这个问题的答案
如何设计带有附加 XAML 的 ItemTemplate?
is:如果 ItemsSource 是 UIElements 的集合,则根本不是。
相反,您应该遵循 ItemsControl 类的基本思想,并将数据项对象的集合分配给 ItemsSource 属性。然后通过 DataTemplate 选择适当的 UI 控件,这些控件的DataType
属性设置为不同数据项的类型。
或者您创建一个派生的 ItemsControl 来覆盖该IsItemItsOwnContainerOverride
方法:
public class MyItemsControl : ItemsControl
{
protected override bool IsItemItsOwnContainerOverride(object item)
{
return false;
}
}
推荐阅读
- c# - 统一摧毁后如何重生坦克?(有几秒钟的延迟)
- reactjs - 根据反应中的逻辑用 span 或 div 标签包装组件
- javascript - 为什么 jQuery 在选择器中链接 .attr() 时只选择一个元素?
- snowflake-cloud-data-platform - 在 Snowsight 中执行多个查询
- java - 找不到 colorpicker-0.0.13.aar (com.github.QuadFlask:colorpicker:0.0.13)
- sql - 如何找到合适尺寸的盒子?
- python-3.x - 具有混合格式的 pandas MultiIndex:将级别 0“%b-%Y”的格式更改为日期时间值
- python - Python:Pandas:Matplotlib:年复一年(x = 月,y = 每年的捐款)
- html - 如何从 Apple Font Book 嵌入字体
- c# - 如何使用 NEST 客户端为弹性搜索索引 Json 数据?