【发布时间】:2017-05-17 17:55:20
【问题描述】:
我又遇到了 XAML 中的绑定问题,我无法自己解决。我有一个ListView 和一个ComboBox。 ListView 的 ItemsSource 位于 TabControl 的视图模型上,ComboBox.ItemsSource 也是如此。如何在此集合上绑定ComboBox?
到目前为止,这是我的代码:
<ListView ItemsSource="{Binding ListViewSource}" SelectedItem="{Binding ListViewSelection}"
ItemTemplate="{DynamicResource ListViewTemplate}">
<ListView.View>
<GridView>
<GridViewColumn Header="...">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding ComboBoxSource}"
SelectedValue="{Binding ...}"
DisplayMemberPath="DisplayName"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn> // ...
这里只是TabViewModel 中ItemsSource 属性的头部:
public ObservableCollection<TypeViewModel> ComboBoxSource { get; set; }
public ObservableCollection<CostViewModel> ListViewSource { get; set; }
是否可以在此属性上绑定CombBox.ItemsSource?
【问题讨论】:
-
在 CellTemplate 中,猜测:
ItemsSource="{Binding DataContext.ComboBoxSource, RelativeSource={RelativeSource AncestorType=ListView}}". -
根据前面的评论,相对源可以做你想做的事。不幸的是,您的问题并不清楚为什么您的
ListView中的每个项目都会有相同的下拉菜单,但是如果由于某种原因相对源方法不适合您的需求,那么每个 @987654335 都不会不合理@ 公开其自己的ComboBoxSource属性,该属性仅代表父视图模型(例如...ComboBoxSource { get { return _parentViewModel.ComboBoxSource; } }。或者取决于这些值的来源,甚至可能是单例。有很多可能的答案。 -
感谢两位的回答。不幸的是,这对我不起作用,但我现在按照 KMCho 在答案 Section { Binding ElementName=ControlName, Path=DataContext.ComboBoxSource } 中解释的方式解决了它