I am trying to create a very simple WPF User Control to represent a digital clock.
I have a couple of things I want client code to be able to change, e.g. foreground text colour, font etc., so I've made some public properties for them. Some of the code is shown below:
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;
}
}
}
I'm using it on another page like this:
<CustomControls:DigitalClock color="#ff000000" />
There are no syntax errors and the clock appears on the screen, but whenever the code hits the line where it's trying to set the colour, I just get an Object reference is not set to an instance of an object
.
I assume this is something to do with the point in time at which the Color property is set, since after the first 'tick' of the timer, the value is no longer null. How do I get around this?