我的项目使用 MVVM,我想将 DataGridComboBoxColumn
绑定(bind)到 View 模型。
组合框应包含项目“<”(键“1”)和“<=”(键“2”)。
首先我有一个带有组合框的observablecollection
:
public ObservableCollection<ArithmeticSignData> LowerComparerItems { get; set; }
这是 ArithmeticSignData 类:
public class ArithmeticSignData
{
public ArithmeticSignData(string key, string value)
{
ArithmeticSignKey = key;
ArithmeticSignValue = value;
}
public string ArithmeticSignKey { get; set; }
public string ArithmeticSignValue { get; set; }
}
当我的 View 模型初始化时,我填充列表 LowerComparerItems:
private void FillLowerComparerItemsList()
{
LowerComparerItems = new ObservableCollection<ArithmeticSignData>();
LowerComparerItems.Add(new ArithmeticSignData("1", "<"));
LowerComparerItems.Add(new ArithmeticSignData("2", "<="));
}
datagrid 的数据来自另一个以 Entity Framework 表为类型的 observablecollection。 该表有一个名为“low_operator”的列。 所以我认为可以通过以下方式绑定(bind)组合框列。 当我打开组合框时,我可以看到项目。 但是在启动应用程序后,表中的值不会转换为“<”或“<=”。
<DataGridComboBoxColumn x:Name="cbc_LowerComparer"
SelectedItemBinding="{Binding low_operator, NotifyOnSourceUpdated=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="ArithmeticSignValue"
Header=" "
Width="30">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Path=DataContext.LowerComparerItems, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Path=DataContext.LowerComparerItems, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
<Setter Property="IsEditable" Value="True"/>
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
最佳答案
您应该将 Selected
ValueBinding
属性设置为您的绑定(bind),并将 SelectedValuePath
属性设置为“ArithmeticSignKey ":
<DataGridComboBoxColumn x:Name="cbc_LowerComparer"
SelectedValueBinding="{Binding low_operator, NotifyOnSourceUpdated=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="ArithmeticSignKey"
DisplayMemberPath="ArithmeticSignValue"
Header=" "
Width="30">
这应该将 low_operator
列设置为所选 ArithmeticSignKey
值的值。如果要将其设置为 ArithmeticSignValue
,则应将列的 SelectedValuePath
属性设置为该列的名称。
关于c# - 如何绑定(bind) WPF DataGrid 的 DataGridComboBoxColumn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42791297/