ComboBox有两个DataContext

时间:2012-11-24 17:17:03

标签: c# wpf mvvm-light

我有一个带有ListView的UserControl ItemTemplate属性中有一个ComboBox我需要为这个ComboBox使用两个datacontext

  1. 来自UserControl的ItemsSource DataContext
  2. ListViewItem的SelectedItem DataContext
  3. 如何实现这个目标?

1 个答案:

答案 0 :(得分:2)

您可以在绑定中使用RelativeSource遍历可视树以查找DataContext for UserControl

而对于ListViewItem,您自Combobox will inherit the DataContext of its parent which is ListViewItem本身就不需要RelativeSource。你的结构看起来有点像这样 -

<UserControl>
   <ListView>
       <ListView.ItemTemplate>
           <DataTemplate>
               <ComboBox ItemsSource="{Binding DataContext.CollectionSource,
                          RelativeSource={RelativeSource FindAncestor, 
                                           AncestorType=UserControl}}"
                         SelectedItem="{Binding YourItemHere}"/>
           </DataTemplate>
       </ListView.ItemTemplate>
   </ListView>
</UserControl>