Tag Property in WPF DataGrid Column

∥☆過路亽.° 提交于 2019-12-28 18:44:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!