Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tag Property in WPF DataGrid Column

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 :(

like image 233
Johannes Wanzek Avatar asked Dec 26 '22 21:12

Johannes Wanzek


1 Answers

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" />
like image 160
Julien Lebosquain Avatar answered Jan 14 '23 05:01

Julien Lebosquain