Обновлено
Лучшее решение - использовать Anonymous Types
.Он работает отлично, см. Следующее подтверждение концепции:
<Window x:Class="AnonymousTypes.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="OnWindowLoaded">
<Grid>
<DataGrid Name="MyDataGrid" ItemsSource="{Binding}" AutoGeneratedColumns="OnMyDataGridAutoGeneratedColumns">
</DataGrid>
</Grid>
</Window>
Кодовый код:
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
namespace AnonymousTypes
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public class Employee
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public int Job { get; set; }
public string Address { get; set; }
}
private ObservableCollection<Employee> _empCollection;
private void OnWindowLoaded(object sender, RoutedEventArgs e)
{
// Generate test data
_empCollection =
new ObservableCollection<Employee>
{
new Employee {Id = 234, Code = "E041", Name = "Employee1", Job = 1, Address = "..."},
new Employee {Id = 245, Code = "E701", Name = "Employee2", Job = 3, Address = "..."},
new Employee {Id = 728, Code = "E001", Name = "Employee3", Job = 9, Address = "..."},
new Employee {Id = 663, Code = "E051", Name = "Employee4", Job = 7, Address = "..."},
};
// Notice that here you can chose the column you want,
// and it can be variable with each query depending on your needs
// Just add the columns you need to the anonymous type
DataContext =
(from i in _empCollection
select new {TheCode = i.Code, TheName = i.Name, TheAddress = i.Address }).ToList();
}
private void OnMyDataGridAutoGeneratedColumns(object sender, EventArgs e)
{
// Now you can change the column names as you need
MyDataGrid.Columns[0].Header = "Header 1 [Code]";
MyDataGrid.Columns[1].Header = "Header 2 [Name]";
MyDataGrid.Columns[2].Header = "Header 3 [Address]";
}
}
}
Вы можете изменить заголовки столбцов после завершения привязки данных, используя AutoGeneratedColumns
событие.