2010-02-01 76 views
1

我有一个应用程序,用户可以在运行时设置datagrid标题背景颜色。我怎样才能做到这一点?我通过下面的代码尝试了相同的操作,但它引发异常。我使用了绑定,但它不起作用。在Silverlight数据网格中设置DataGridHeaderBackground的背景颜色

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

“投掷期望”?如果您确切地包含了例外情况,可能会有所帮助? – AnthonyWJones 2010-02-01 12:43:47

回答

0

没有进一步的细节(例如你得到的例外),很难看出你为什么会得到例外。我怀疑style变量有一个空引用。

我也怀疑它的null的原因是“DataGridHeaderStyle”不存在于this对象的资源字典中,我猜想它是UserControl。为了获取Style,您需要执行此操作,查看Resources属性中包含Style的实际FrameworkElement对象。 (注意对资源的编程访问不会使搜索父母资源的可视化树级联起来)。

但是,假设您可以解决您仍然有问题。在Setters colleciton本身上使用SetValue与您实际需要做的事完全不同。

你必须这样做: -

style.Setters.Add(new Setter(DataGridColumnHeader.BackgroundProperty, new SolidColorBrush(Colors.Red)); 

当然如果风格不已经包含了财产Setter这仅适用。因此更强大的版本是: -

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