如何在WPF数据网格中为可观察集合指定列标题?

时间:2015-08-18 04:01:32

标签: c# wpf datagrid

我有以下代码,我正在使用:

填充WPF数据网格
var customers = new ObservableCollection<Customer>();

foreach (
    var customer in
        collListItem.Select(
            item =>
            new Customer
                {
                    Persona = item["Persona"].ToString(),
                    CustomerName = item["Title"].ToString()
                }))
{
    customers.Add(customer);
}

this.dataGridOutstandingOrders.ItemsSource = customers;

基于我的客户类:

public class Customer
{
    /// <summary>
    /// Gets or sets the persona.
    /// </summary>
    public string Persona { get; set; }

    /// <summary>
    /// Gets or sets the customer name.
    /// </summary>
    public string CustomerName { get; set; }
}

问题是,一旦我将数据绑定到WPF数据网格,列就会以Customer();中的变量名称出现。相反,我希望能够指定列的名称(例如,CustomerName将是Customer Name)。有没有办法在我的客户类中使用注释来执行此操作?

2 个答案:

答案 0 :(得分:1)

我不确定您是如何在Xaml中定义android.permission.NFC的,但下面的代码应该有效。

DataGrid

答案 1 :(得分:1)

您可以在CustomerName属性中添加[Display(Name="Customer Name")]属性:

public class Customer
{
    /// <summary>
    /// Gets or sets the persona.
    /// </summary>
    public string Persona { get; set; }

    /// <summary>
    /// Gets or sets the customer name.
    /// </summary>
    [Display(Name="Customer Name")]
    public string CustomerName { get; set; }
}

编辑: 您需要为datagrid处理AutoGeneratingColumns事件:

private void DG_OnAutoGeneratingColumns(object sender,DataGridAutoGeneratingColumnEventArgs e)
System.ComponentModel.PropertyDescriptor propdesc = e.PropertyDescriptor as System.ComponentModel.PropertyDescriptor;
System.ComponentModel.DataAnnotations.DisplayAttribute displayAttrib =
            pd.Attributes[typeOf(ComponentModel.DataAnnotations.DisplayAttribute)] as System.ComponentModel.DataAnnotations.DisplayAttribute;
if(displayAttrib!=null)
{
   e.Column.Header = displayAttrib.Name;
}