【发布时间】:2018-07-20 01:52:16
【问题描述】:
这是为了回答我自己的问题。
在 WPF 中,我以编程方式创建了一个 DataGridComboBoxColumn 并将其绑定到对象的 ObservableCollection 并将 DisplayMemberPath 设置为对象属性之一。当 Combo Box 下拉菜单打开时,DisplayMember 按预期工作,我看到了该属性。但是,当组合框失去焦点而不是在组合框中看到属性值时,我会看到类名,例如“{namespace1.Warehouses}”而不是“Warehouse A”
有问题的代码(简化/修改):
数据网格项目代码
public class Item{
public Item(){}
private Warehouse itemWarehouse;
public Warehouse Item_Warehouse{
get{ return itemWarehouse; }
set{ itemWarehouse=value; }
}
}
仓库类
public class Warehouse{
private string label;
public Warehouse (string theLabel){
label=theLabel;
}
public string Label{
get{ return label; }
set{ label=value; }
}
}
在 xaml.cs 中,使用此代码将导致 Combobox 显示重置为类名,而不是 Warehouse.Label,就像在组合框关闭后应该显示的那样。
DataGridComboBoxColumn dataCBColumn = new DataGridComboBoxColumn();
//below three lines cause the problem. When programmatically setting
//DisplayMemberPath it should not be done this way
dataCBColumn.EditingElementStyle = new Style();
dataCBColumn.EditingElementStyle.TargetType = typeof(ComboBox);
dataCBColumn.EditingElementStyle.Setters.Add(new Setter(ComboBox.DisplayMemberPathProperty, "Label"));
//-------------------------------------------------------------------
dataCBColumn.ItemsSource = WareHouses; //where WareHouses is of type ObservableCollection<WareHouse>
dataCBColumn.SelectedItemBinding = new Binding("Item_Warehouse"); //this Warehouse refers to the Datagrid Item 'Warehouse' object.
【问题讨论】: