【问题标题】:What's the syntax for setting an ItemsControl's ItemSource to a CompositeCollection?将 ItemsControl 的 ItemSource 设置为 CompositeCollection 的语法是什么?
【发布时间】:2015-04-28 10:15:51
【问题描述】:

我正在尝试使用复合集合作为 ItemsControl 的 ItemsSource。然后 ItemsControl 应根据复合集合中的对象类型显示不同的控件。

根据这个问题:

How do you bind a CollectionContainer to a collection in a view model?

我看到我不能直接将复合集合绑定为 ItemsSource,像这样:

ItemsSource="{Binding CombinedCollection}"

所以我在 ItemsControl 资源中创建了复合集合:

<ItemsControl.Resources>
    <CompositeCollection x:Key="cmpcol">
        <CollectionContainer Collection="{Binding TimeSlots}"/>
        <CollectionContainer Collection="{Binding Items}"/>
    </CompositeCollection>
    <DataTemplate DataType="{x:Type tg:TimeSlot}">
        <tgvw:TimeSlotRect/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type tg:Item}">
        <TextBox></TextBox>
    </DataTemplate>         
</ItemsControl.Resources>

我现在如何将复合集合设置为 ItemsSource?我似乎无法理解语法。我猜是这样的:

<ItemsControl.ItemsSource>
   <!--Something Here-->
</ItemsControl.ItemsSource>

顺便说一句,这里的答案https://stackoverflow.com/a/5473443/2591770 设法直接绑定到视图模型中的集合 - 但我无法分辨示例中的“数据”对象是什么。

【问题讨论】:

    标签: c# wpf xaml mvvm


    【解决方案1】:

    在视图模型中创建一个对象类型的集合。并在其中添加您的复合集合。然后将 List 绑定到 Items 控件的 Item 源。

    【讨论】:

    • 在视图模型中应该是 ObservableCollection、Collection 还是 List
    • ObservableCollection 会很好。它会自动升起。
    • 似乎不起作用我创建了 oc 并添加了复合集合。可能是 XAML 中的问题?
    【解决方案2】:

    解决了。

    事实证明,在视图模型中:

    CompositeCollection CombinedCollection = new CompositeCollection();
    

    不等于:

    CombinedCollection = new CompositeCollection();
    

    我使用了后者,它适用于:

    ItemsSource="{Binding CombinedCollection}"
    

    菜鸟失误!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多