![](/img/trans.png)
[英]WPF DataGrid - Dynamically Bind DataGridComboBoxColumn based on row
[英]How to bind a DataGridComboBoxColumn of a WPF DataGrid
我的項目使用 MVVM,我想將DataGridComboBoxColumn
綁定到視圖模型。
組合框應具有項目“<”(鍵為“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; }
}
當我的視圖模型被初始化時,我填充列表 LowerComparerItems:
private void FillLowerComparerItemsList()
{
LowerComparerItems = new ObservableCollection<ArithmeticSignData>();
LowerComparerItems.Add(new ArithmeticSignData("1", "<"));
LowerComparerItems.Add(new ArithmeticSignData("2", "<="));
}
數據網格的數據來自另一個以實體框架表為類型的 observablecollection。 該表有一個名為“low_operator”的列。 所以我認為可以通過以下方式綁定組合框列。 當我打開組合框時,我可以看到項目。 但是在啟動應用程序后,表中的值不會轉換為“<”或“<=”。
<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
Value Binding
屬性設置為您的綁定,並將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
屬性設置為該列的名稱。
像這樣編輯您的代碼:
<DataGridComboBoxColumn x:Name="cbc_LowerComparer"
ItemsSource="{Binding LowerComparerItems, UpdateSourceTrigger=PropertyChanged}"
SelectedItemBinding="{Binding low_operator, NotifyOnSourceUpdated=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="ArithmeticSignValue"
Header=" "
Width="30">
而不是 SelectedItemBinding 使用這個...
SelectedValueBinding="{Binding low_operator}"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.