没有进一步的细节(例如你得到的例外),很难看出你为什么会得到例外。我怀疑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));
“投掷期望”?如果您确切地包含了例外情况,可能会有所帮助? – AnthonyWJones 2010-02-01 12:43:47