【发布时间】:2015-10-06 08:23:58
【问题描述】:
您好,我有一个包含两列的数据网格。如下所示:
<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 已更改。 下面是一个类,它是数据网格的数据上下文:
public class MyClass
{
public string TeamName{get;set;}
public string Prefix{get;set;}
}
// DataGrid.DataContext is ObservableCollection<MyClass>
所以 AllowedPrefixes 集合在 ComboBox 中正确显示,但 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}">
【问题讨论】:
-
请添加错误或说明它如何不工作
-
你可能想使用
SelectedItem,而不是SelectedValue- stackoverflow.com/questions/4902039/… -
没有错误,只是没有更新 viemodels 前缀属性。所选项目不会改变任何内容。
-
继续 DownVoters - 继续 DownVoting 而不是帮助。甚至不解释......
-
在Binding中添加
Mode=TwoWay,默认可能是OneWay
标签: wpf mvvm combobox datagridtemplatecolumn