【发布时间】:2019-11-27 15:52:34
【问题描述】:
我在这个网站上看到过一些与我的问题类似的帖子,例如 this one 和 this one 但我还没有得到这个为我工作。
我有一个由 Foo 类型的对象列表绑定的 datagrid,并且我为每一行添加了一个 combobox。 ComboBox ItemSource 不是 Foo 类的一部分,而是在视图模型中创建的。我知道这样做意味着此组合框对于每一行都是相同的,但我的 Xaml 中没有办法将 SelectedItem 过滤到仅行吗?
这是我的 Xaml:
<DataGridTemplateColumn Header="Foo Column" Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox
ItemsSource="{Binding Mode=OneWay,Path=DataContext.FooCollection,
RelativeSource= {RelativeSource FindAncestor,
AncestorType={x:Type DataGrid}}}"
SelectedItem="{Binding DataContext.SelectedComboBoxItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,
RelativeSource= {RelativeSource FindAncestor,
AncestorType={x:Type DataGrid}}}">
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
这是我的 ViewModel:
public ObservableCollection<string> FooCollection
{
get
{
return _FooCollection;
}
set
{
if (_FooCollection != value)
{
_FooCollection = value;
RaisePropertyChanged(nameof(FooCollection));
}
}
}
private ObservableCollection<string> _FooCollection = new ObservableCollection<string>();
public string SelectedComboBoxItem
{
get
{
return __SelectedComboBoxItem;
}
set
{
if (_SelectedComboBoxItem != value)
{
_SelectedComboBoxItem = value;
RaisePropertyChanged(nameof(SelectedComboBoxItem));
}
}
}
private string _SelectedComboBoxItem = string.Empty;
我看到我的组合框集合已填充,但是当我进行选择时,每个其他组合框都会获得相同的值。谁能帮我理解我做错了什么?非常感谢。
【问题讨论】:
-
能否请您发布 ViewModel。似乎datagrid的所有组合框都绑定到
SelectedComboBoxItem。它应该绑定到property of item的集合,该集合绑定到DataGrid -
@user1672994 可以做
-
SelectedComboBoxItem应该是FooCollection的一部分。将属性更改为public ObservableCollection<MyType> FooCollection,这应该定义附加属性SelectedComboBoxItem,然后将绑定更改为SelectedItem="{Binding SelectedComboBoxItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged} -
FooCollection绑定到每个组合框,将SelectedComboBoxItem添加到此集合并不能解决问题。 @user2529011 你能分享DataGrid的完整xaml 吗?SelectedComboBoxItem应该是Foo类型的一部分