【问题标题】:C#/WPF NullReference Exception on filling Rectangle with App Settings ValueC#/WPF NullReferenceException 用 Appsettings 值填充矩形
【发布时间】:2013-10-27 13:38:53
【问题描述】:

我正在尝试用settings.settings 的值填充rectangle。但它会引发 NullReference 错误。当我使用 MessageBox 显示设置时,它不是空的。 NullRefference exception 由 Rectangle 触发

 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:

<Button Click="btnBackground_Click" Grid.Row="0" Grid.Column="1" Name="btnBackground">
                    <Button.Template>
                        <ControlTemplate>
                            <Rectangle Name="rectBackground" Stroke="Black" Fill="#FFFFFF"></Rectangle>
                        </ControlTemplate>
                    </Button.Template>
                </Button>

当我创建一个新的 Rectangle 对象时,我不能再改变颜色了。

【问题讨论】:

  • 第一个代码sn-p放在哪里?
  • 在 Window_Loaded 中。但即使我将它放在 TabControl 的 SelectionChanged 事件中,它也会崩溃
  • colorBG 的值是多少?您确定使用正确/可转换的颜色字符串值正确存储它吗?
  • 你不能在RectangleFill上使用TemplateBinding来使用ButtonBackgound吗?然后更新 Button 的 Background 会更容易,这反过来会更新 Rectangle 的 Fill
  • TemplateBinding &lt;Rectangle Fill="{TemplateBinding Background}" Name="rectBackground" Stroke="Black" /&gt; 的正确方法

标签: c# wpf colors nullreferenceexception rectangles


【解决方案1】:

实现您想要的最简单的方法是在Rectangle Fill 属性上使用TemplateBinding 以使用Button's Background。然后,将按钮的背景设置为应用设置中的值,这反过来会更新 Rectangle 的 Fill

示例代码如下:

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

【讨论】:

    猜你喜欢
    • 2017-04-27
    • 2012-07-03
    • 2012-05-10
    • 2015-08-20
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多