2013-08-30 45 views
1

我正在尝试将列表框的itemsSource设置为compositecollection。在wpf中使用复合集合获取所选项目

<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的绑定不起作用。当一个项目被选中时,如何在viewmodel中获取选定的项目?

+0

SelectedSourceViewDetail的类型是什么? – Nitin

+0

是的,我明白了。设置类型为object返回一个listboxitem,但它不是我想要的。我想要所选项目的datacontext。 listboxitem的datacontext类型和collectioncontainer中的项目是相同的。 –

+0

然后我会建议你使用转换器,它返回CompositeCollection并将该集合绑定到ItemsSource。您正在itemsSource中添加Listboxitem和collectioncontatiner。 CompositeCollection将收集设置和ExtraViews – Nitin

回答

0

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

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

谢谢

+0

@Victor是否解决了您的问题? – Nitin