Search code examples
c#wpfdatagriddatatriggerprogrammatically-created

WPF Programmatically add DataGridTextColumn with DataTrigger


I have a DataGrid that is made of dynamically by the user. That means each time it runs the columns could and will be very different. Each column is programmatically added for that reason. I need to add some DataTriggers to it so figured this would work:

Style style = new Style();
style.TargetType = typeof(DataGridTextColumn);
DataTrigger tg = new DataTrigger()
{
    Binding = new Binding(value),
    Value = "bad data"
};
tg.Setters.Add(new Setter()
{
    Property = UIElement.VisibilityProperty,
    Value = Visibility.Hidden
});

While this gives no errors in the IDE when run it crashes and gives me 'DataGridTextColumn' type must derive from FrameworkElement or FrameworkContentElement.

What is the correct way of adding a DataTrigger to a DataGridTextColumn Programmatically


Solution

  • You need to use typeof(DataGridCell). The trigger should be applied to the Cell itself, not the Column.