首页 > 解决方案 > 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>

标签: c#wpfxamlbinding

解决方案


查看参考源会发现IsItemItsOwnContainerOverrideItemsControl 类的方法具有以下实现:

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

推荐阅读