【问题标题】:WPF DataGridComboBoxColumn DisplayMember resets to class name after combo box loses focus when binding programmaticallyWPF DataGridComboBoxColumn DisplayMember 在以编程方式绑定时组合框失去焦点后重置为类名
【发布时间】: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.

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    以下是 xaml.cs 的正确代码 直接使用 dataCBColumn.DisplayMemberPath 而不是使用 Element Style 进行编辑。

    DataGridComboBoxColumn dataCBColumn = new DataGridComboBoxColumn();
    dataCBColumn.DisplayMemberPath = "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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-30
      相关资源
      最近更新 更多