Search code examples
wpfdatagriddatagridcolumn

WPF Datagrid Column - How to attach a tag object programatically?


Folks,

I need to add a "tag" property to a programatically created WPF DataGridColumn. I saw a nice example at Tag Property in WPF DataGrid Column.

However, this example is using the tag property in a statically defined xaml file. In my case, I need to do something similar dynamically. Can someone please tell me how I can achieve this?

Thank you in advance for your help.


Solution

  • Ok. I figured out what needs to be done.

    First, declare a static DependencyProperty:

     public static readonly DependencyProperty TagProperty = DependencyProperty.RegisterAttached(
         "Tag",
         typeof(object),
         typeof(DataGridColumn),
         new FrameworkPropertyMetadata(null));
    

    Now, simply use it to get/set any object.

    DataGridTextColumn col = new DataGridTextColumn(...)
    col.SetValue(TagProperty, myObject);
    MyObject o = (MyObject) col.GetValue(TagProperty);
    

    Hope you find this useful.

    Regards,
    Peter