简体   繁体   English

WPF ItemsControl绑定到UserControls

[英]WPF ItemsControl bound to UserControls

An ItemsControl binding to a collection of UserControl objects works fine. 绑定到UserControl对象集合的ItemsControl正常工作。 However, I would like to apply additional XAML, such as a Border , etc. 但是,我想应用其他XAML,例如Border等。

However, instead of a Border with the UserControl, only the UserControl itself is rendered. 但是,不是呈现UserControl的Border ,而是仅呈现UserControl本身。 The <ItemsControl.ItemTemplate> does not seem to have any effect. <ItemsControl.ItemTemplate>似乎没有任何作用。

Question: How can I design an ItemTemplate with additional XAML? 问题:如何设计带有附加XAML的ItemTemplate? Currently, this tag seems to be "ignored". 当前,该标签似乎被“忽略”。


ViewModel: ObservableCollection<UserControl> MyUserControls ViewModel: 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>

A look at the reference source reveals that the IsItemItsOwnContainerOverride method of the ItemsControl class has this implementation: 查看参考源可以发现ItemsControl类的IsItemItsOwnContainerOverride方法具有以下实现:

protected virtual bool IsItemItsOwnContainerOverride(object item)
{
    return (item is UIElement);
}

So if you pass a collection of UIElements to the ItemsSource of an ItemsControl, these elements are used directly as item containers, without the usual wrapping inside a ContentPresenter . 因此,如果将UIElements的集合传递给ItemsControl的ItemsSource,则这些元素将直接用作项目容器,而无需在ContentPresenter进行通常的包装。 Hence no ItemTemplate is applied at all. 因此根本没有应用ItemTemplate

So the answer to the question 所以问题的答案

How can I design an ItemTemplate with additional XAML? 如何设计带有附加XAML的ItemTemplate?

is: Not at all if the ItemsSource is a collection of UIElements. 是:如果ItemsSource是UIElements的集合,则完全没有。

You should instead follow the basic idea of the ItemsControl class, and assign a collection of data item objects to the ItemsSource property. 相反,您应该遵循ItemsControl类的基本思想,并将数据项对象的集合分配给ItemsSource属性。 Then select appropriate UI controls by DataTemplates that have their DataType property set to the types of the different data items. 然后通过DataTemplates选择合适的UI控件,这些控件的DataType属性设置为不同数据项的类型。


Or you create a derived ItemsControl which overrides the IsItemItsOwnContainerOverride method: 或者,您创建派生的ItemsControl,它重写IsItemItsOwnContainerOverride方法:

public class MyItemsControl : ItemsControl
{
    protected override bool IsItemItsOwnContainerOverride(object item)
    {
        return false;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM