|
using System;
using System.Reflection;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows.Interactivity;
namespace AttributtedDataColumn
{
public class ColumnHeaderBehavior : Behavior<DataGrid>
{
protected override void OnAttached()
{
AssociatedObject.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(OnAutoGeneratingColumn);
}
protected override void OnDetaching()
{
AssociatedObject.AutoGeneratingColumn -= new EventHandler<DataGridAutoGeneratingColumnEventArgs>(OnAutoGeneratingColumn);
}
protected void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
string displayName = GetPropertyDisplayName(e.PropertyDescriptor);
if (!string.IsNullOrEmpty(displayName))
{
e.Column.Header = displayName;
}
else
{
e.Cancel = true;
}
}
protected static string GetPropertyDisplayName(object descriptor)
{
PropertyDescriptor pd = descriptor as PropertyDescriptor;
if (pd != null)
{
DisplayNameAttribute attr = pd.Attributes[typeof(DisplayNameAttribute)] as DisplayNameAttribute;
if ((attr != null) && (attr != DisplayNameAttribute.Default))
{
return attr.DisplayName;
}
}
else
{
PropertyInfo pi = descriptor as PropertyInfo;
if (pi != null)
{
Object[] attrs = pi.GetCustomAttributes(typeof(DisplayNameAttribute), true);
foreach (var att in attrs)
{
DisplayNameAttribute attribute = att as DisplayNameAttribute;
if ((attribute != null) && (attribute != DisplayNameAttribute.Default))
{
return attribute.DisplayName;
}
}
}
}
return null;
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.