问题
I need to save an string inside a Datagrid Column which differs from the Header.
This is needed because I generate a Datagrid dynamically and want to translate the Column Headers while generating them. Then I bind the whole XAML to a ContentControl.
No problem till here... But I want to reorder and resize the columns, so I need to lookup them afterwoods. For this I need the original (not translated) ColumnHeader.
In my opinion a Tag property of the column would solve this problem, but there is no :(
回答1:
In WPF, you have virtually unlimited "Tag" properties by using Attached Properties. An attached property can be set on any DependencyObject
. A good example of such an attached property is Grid.Row
. Since you can define them, you also have the possibility of naming them something more meaningful than Tag.
Sample code for defining an attached property:
public static class SomeClass {
public static readonly DependencyProperty TagProperty = DependencyProperty.RegisterAttached(
"Tag",
typeof(object),
typeof(SomeClass),
new FrameworkPropertyMetadata(null));
public static object GetTag(DependencyObject dependencyObject) {
return dependencyObject.GetValue(TagProperty);
}
public static void SetTag(DependencyObject dependencyObject, object value) {
dependencyObject.SetValue(TagProperty, value);
}
}
Usage :
<DataGridColumn SomeClass.Tag="abc" />
来源:https://stackoverflow.com/questions/11535894/tag-property-in-wpf-datagrid-column