嗨所以我有一个包含两列的数据网格 . 它看起来如下:
<DataGrid ItemsSource="{Binding MyCollection}">
<DataGrid.Columns>
<DataGridTextColumn Width="85*" Header="Team Name" Binding="{Binding TeamName}"/>
<DataGridTemplateColumn Header="Prefix">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}},Path=DataContext.AllowedPrefixes}"
SelectedValue="{Binding Prefix}">
//SelectedValue="{Binding Prefix}" - this is not working i also tried SelectedItem
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
就像你可以看到我有一个带有ComboBox的DataGridTemplateColumn . 我已将ComboBox ItemsSource绑定到一个包含一些固定值的集合 . 现在我想将ComboBox的SelectedValue绑定到MyClass的Prefix属性(这是我的DataGrid的DataContext) . 但是因为我将这个ComboBox的ItemsSource设置为其他Collection这个绑定不起作用我认为datacontext已经改变了 . 下面是一个类,它是datagrid的datacontext:
public class MyClass
{
public string TeamName{get;set;}
public string Prefix{get;set;}
}
// DataGrid.DataContext is ObservableCollection<MyClass>
因此,在ComboBox中正确显示AllowedPrefixes集合,但未更新Prefix属性 . 我应该如何正确地使这个SelectedValue绑定?
编辑 .
请注意,ComboBox ItemsSource与我想用SelectedValue更新的不同
编辑 .
我认为它不起作用,因为我将ComboBox ItemsSource设置为不同的集合 . 我尝试过以下但没有成功:
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}},Path=DataContext.AllowedPrefixes}"
SelectedValue="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridTextColumn}}, Path=DataContext.Prefix, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
2 回答
请尝试以下内容为您的
ComboBox
:如果
DataGrid
在UserControl
内,而不是Windows
,则将AncestorType更改为UserControl
好吧,尽管有你们所有人 - 那些不知道答案的人和没有解释的DownVoted我 . 我找到了解决方案 . 我发布它可能会在将来使用它,我必须将NotifyOnTargetUpdated设置为true: