C#/WPF NullReference使用应用程序设置值填充矩形时出现异常

C#/WPF NullReference使用应用程序设置值填充矩形时出现异常,c#,wpf,colors,nullreferenceexception,rectangles,C#,Wpf,Colors,Nullreferenceexception,Rectangles,我试图用settings.settings的值填充矩形。但是它抛出了一个空引用错误。当我用消息框显示设置时,它不是空的。nullreference异常由矩形触发 var rect = btnBackground.Template.FindName("rectBackground", btnBackground) as Rectangle; rect.Fill = new SolidColorBrush((Color)ColorConverter.ConvertFromStrin

我试图用
settings.settings
的值填充
矩形。但是它抛出了一个空引用错误。当我用消息框显示设置时,它不是空的。
nullreference异常
由矩形触发

 var rect = btnBackground.Template.FindName("rectBackground", btnBackground) as Rectangle;
        rect.Fill = new SolidColorBrush((Color)ColorConverter.ConvertFromString((PawnStar.Properties.Settings.Default.colorBG)));                                            // PawnStar.Properties.Settings.Default.colorBG
        colorBG = (Color)ColorConverter.ConvertFromString((PawnStar.Properties.Settings.Default.colorBG));
WPF:



当我创建一个新的矩形对象时,我不能再更改颜色。

实现您所尝试的最简单的方法是在
矩形
填充
属性上使用
按钮的
背景
。然后,将按钮的背景设置为应用程序设置中的值,这反过来会更新矩形的填充

示例代码如下:

<Rectangle Fill="{TemplateBinding Background}" Name="rectBackground" Stroke="Black" />


在加载的窗口中,第一个代码段放在哪里。但即使我将它放在TabControl的SelectionChanged事件中,它也会崩溃
colorBG
的值是多少?您确定使用正确的/可转换的颜色字符串值正确存储了它吗?您不能在
矩形上使用
模板绑定
填充
来使用
按钮的
背景
?然后更新按钮的
背景将更容易,这反过来又会更新矩形的
填充
<Rectangle Fill="{TemplateBinding Background}" Name="rectBackground" Stroke="Black" />