【问题标题】:Getting Selected Item with composite collection in wpf在wpf中使用复合集合获取选定项
【发布时间】:2013-09-03 02:41:03
【问题描述】:

我正在尝试将列表框的 itemsSource 设置为复合集合。

<ListBox x:Name="moduleMenu" SelectedItem="{Binding SelectedSourceViewDetail}">
                        <ItemsControl.ItemsPanel>
                            <ItemsPanelTemplate>
                                <StackPanel Orientation="Horizontal"/>
                            </ItemsPanelTemplate>
                        </ItemsControl.ItemsPanel>

                        <ListBox.ItemsSource>
                            <CompositeCollection>
                                <ListBoxItem DataContext="{Binding SourceModule.Settings}" Content="{Binding Name}"/>
                                <CollectionContainer Collection="{Binding SourceModule.ExtraViews}" />
                            </CompositeCollection>
                        </ListBox.ItemsSource>
                    </ListBox>

但是与 selectedItem 的绑定不起作用。选择项目时如何在视图模型中获取所选项目?

【问题讨论】:

  • SelectedSourceViewDetail的类型是什么?
  • 是的,我明白了。将类型设置为对象返回了一个列表框项,但这不是我想要的。我想要所选项目的数据上下文。 listboxitem的datacontext类型和collectioncontainer中的item是一样的。
  • 那么我建议您使用返回 CompositeCollection 并将该集合绑定到 ItemsSource 的转换器。您正在 itemsSource 中添加 Listboxitem 和 collectioncontatiner。 CompositeCollection 将是 Settings 和 ExtraViews 的集合

标签: .net wpf mvvm binding compositecollection


【解决方案1】:

而不是像在 xaml 中那样设置 ItemsSource。我建议您使用返回 CompositeCollection 并将该集合绑定到 ItemsSource 的转换器。 CompositeCollection 将是 Settings 和 ExtraViews 的集合

您的绑定看起来像ItemsSource = "{Binding SourceModel, Converter={StaticResource myConverter}}"。在转换器的 Convert 方法中,从 sourcemodel.Settings 和 sourcemodel.ExtraViews 创建复合集合并返回。

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 2013-10-27
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多