Without further details (such as the exception you are getting) its difficult to see why you are getting an exception. I suspect that the style
variable has a null reference.
I also suspect that the reason its null is that the "DataGridHeaderStyle" doesn't exist in the resource dictionary of the this
object, which I would guess is a UserControl
. In order to acquire the Style
you need to do this look up on the actual FrameworkElement
object that holds the Style
in its Resources
property. (Note programmatic access to the resources does not cascade up the visual tree searching the resource of parents).
However, assuming you can fix that you still have a problem. The use of SetValue
on the Setters
colleciton itself is nothing like what you actually need to be doing.
You need to be doing this:-
style.Setters.Add(new Setter(DataGridColumnHeader.BackgroundProperty, new SolidColorBrush(Colors.Red));
Of course this only works if the style doesn't already contain an Setter
for the property. Hence a more robust version is:-
var setter = style.Setters
.OfType<Setter>()
.Where(s => s.Property == DataGridColumnHeader.BackgroundProperty)
.FirstOrDefault();
if (setter != null)
setter.Value = new SolidColorBrush(Colors.Red);
else
style.Setters.Add(new Setter(DataGridColumnHeader.BackgroundProperty, new SolidColorBrush(Colors.Red));