开发者

Set the background color of DataGridHeaderBackground in Silverlight datagrid

开发者 https://www.devze.com 2022-12-18 12:19 出处:网络
I have a application where user can set the datagrid header background color in runtime. How can I do this? I tried the same through the following code but it is throwing exception.I have used b开发者

I have a application where user can set the datagrid header background color in runtime. How can I do this? I tried the same through the following code but it is throwing exception.I have used b开发者_JAVA技巧inding and but it's not working.

var style = this.Resources["DataGridHeaderStyle"] as Style;
style.Setters.SetValue(DataGridColumnHeader.BackgroundProperty, "Red");


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));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号