【发布时间】:2015-02-17 14:16:27
【问题描述】:
我正在尝试创建一个非常简单的 WPF 用户控件来表示数字时钟。
我有几件事希望客户端代码能够更改,例如前景文本颜色、字体等,所以我为它们创建了一些公共属性。部分代码如下所示:
public partial class DigitalClock : System.Windows.Controls.UserControl
{
public string Color { get; set; }
private Timer timer;
private string DisplayString { get { return DateTime.Now.ToString("dd-MM-yy HH:mm:ss"); } }
public DigitalClock()
{
InitializeComponent();
this.timer = new Timer();
this.timer.Tick += new EventHandler(UpdateClock);
this.timer.Interval = 1000;
this.timer.Enabled = true;
this.timer.Start();
UpdateClock(null, null);
try
{
//exception thrown here as this.Color is null
Color color = (Color)ColorConverter.ConvertFromString(this.Color);
tbClock.Foreground = new SolidColorBrush(color);
}
catch (Exception ex)
{
Console.WriteLine(">>>" + ex.Message);
}
}
private void UpdateClock(object sender, EventArgs e)
{
tbClock.Text = DisplayString;
}
}
}
我在这样的另一个页面上使用它:
<CustomControls:DigitalClock color="#ff000000" />
没有语法错误,时钟出现在屏幕上,但每当代码到达尝试设置颜色的行时,我就会得到一个Object reference is not set to an instance of an object。
我认为这与设置 Color 属性的时间点有关,因为在计时器的第一个“滴答”之后,该值不再为空。我该如何解决这个问题?
【问题讨论】:
-
尝试在构造函数中将默认值设置为Color。
-
为什么不在 XAML 中设置颜色?或者只是在构造函数中设置它。另外,如果你按照你已经做的方式做,你不能在分配它之前输入一行:if (color!=null)
-
尝试添加 Usercontrol Loaded 方法并将其设置在那里?
-
您的 XAML 的执行方式类似于:
var ctl = new DigitalClock(); ctl.Color = #ff000000;。构造函数代码在第一行运行,此时 Color 属性为null。尝试改用Loaded事件或Color属性的设置器。另外,我会使用 DependencyProperty 进行调查以允许绑定:)