以下解决方案如何:
如下所示的解决方案:
dataGrid.SetValue(
DataGridUtilities.ColumnHeadersProperty,
new Dictionary<string, string> {
{ "Foo", "The Foo" },
{ "Bar", "The Bar" },
});
dataGrid.ItemsSource = (from item in someCollection
select{
Foo = item.SomeField,
Bar = item.SomeOtherField,
}).ToList();
那么接下来是一些关于附加属性的代码:
public static class DataGridUtilities
{
public static IDictionary<string,string> GetColumnHeaders(
DependencyObject obj)
{
return (IDictionary<string,string>)obj.GetValue(ColumnHeadersProperty);
}
public static void SetColumnHeaders(DependencyObject obj,
IDictionary<string, string> value)
{
obj.SetValue(ColumnHeadersProperty, value);
}
public static readonly DependencyProperty ColumnHeadersProperty =
DependencyProperty.RegisterAttached(
"ColumnHeaders",
typeof(IDictionary<string, string>),
typeof(DataGrid),
new UIPropertyMetadata(null, ColumnHeadersPropertyChanged));
static void ColumnHeadersPropertyChanged(DependencyObject sender,
DependencyPropertyChangedEventArgs e)
{
var dataGrid = sender as DataGrid;
if (dataGrid != null && e.NewValue != null)
{
dataGrid.AutoGeneratingColumn += AddColumnHeaders;
}
}
static void AddColumnHeaders(object sender,
DataGridAutoGeneratingColumnEventArgs e)
{
var headers = GetColumnHeaders(sender as DataGrid);
if (headers != null && headers.ContainsKey(e.PropertyName))
{
e.Column.Header = headers[e.PropertyName];
}
}
}
DisplayNameAttribute
。另一个原因是计划使用Dynamic Linq,以便在运行时让用户选择列。 - TheOtherGuy