2015-08-18 4 views
0

У меня есть следующий код, который я заселять DataGrid 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 datagrid столбцы проходят как имена моих переменных в Customer();. Вместо этого я хотел бы указать имя столбца (например, CustomerName будет Customer Name). Есть ли способ сделать это с аннотациями в моем классе клиентов?

ответ

1

Вы можете добавить [Display(Name="Customer Name")] атрибут CUSTOMERNAME собственности:

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; } 
} 

Отредактировано: Вы должны обрабатывать AutoGeneratingColumns событие для DataGrid:

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; 
} 
+0

Я проверю это снова, но я верю, что это не работало для меня (см. Комментарий к ответу Хари) – Codingo

1

Я не уверен, как вы определили свой DataGrid в Xaml, но ниже код должен работать.

<DataGrid Name="dgUsers" AutoGenerateColumns="False"> 
    <DataGrid.Columns> 
     <DataGridTextColumn Header="Person" Binding="{Binding Persona }" /> 
     <DataGridTextColumn Header="Customer Name" Binding="{Binding CustomerName }" /> 
    </DataGrid.Columns> 
</DataGrid> 
+0

Спасибо, но это на самом деле не ответ вопрос. Я ищу способ приблизиться к этому за пределами XAML. В идеале я хотел бы использовать аннотации данных, поскольку datagrids, кажется, игнорируют аннотацию DisplayName. – Codingo

Смежные вопросы