I'm trying to create a small countdown (3,2,1) in the middle of a canvas in a WPF Windows.
So Far so easy, but I have some unexpected troubles setting the Label in the middle of the Canvas.
I learned from this Thread What is the difference between Width and ActualWidth in WPF? ,that the Width and Height ar NaN, when they're automatically set, which is fine. But ActualWidth/Height are 0 and I can't see any other Properties, which give me the value I need. My code is looking like this:
void CountDown(object sender, ElapsedEventArgs e)
{
Application.Current.Dispatcher.Invoke(() =>
{
TryRemoveLabel();
if (_countDown > 0)
{
Label lbl = CreateCountDownLabel();
_gameField.Children.Add(lbl);
Canvas.SetZIndex(lbl, 3);
double left = (_gameField.ActualWidth / 2) - (lbl.Width / 2);
Canvas.SetLeft(lbl, left);
double top = (_gameField.ActualHeight / 2) - (lbl.Height / 2);
Canvas.SetTop(lbl, top);
}
else
{
_timer.Stop();
_startCallback();
}
});
}
So CountDown is the Elapsed event of the _timer. I remove the Label and as long as Countdown is > 0, I create a new one. But as you see, not lbl.Width nor ActualWidth etc. are working.
The CreateCountDownLabel is looking like this:
private Label CreateCountDownLabel()
{
Label result = new Label();
result.FontSize = 100;
//result.Height = 300;
//result.Width = 300;
switch (_countDown)
{
case 3:
result.Foreground = Brushes.LightGreen;
break;
case 2:
result.Foreground = Brushes.LightBlue;
break;
case 1:
result.Foreground = Brushes.LightPink;
break;
}
result.Content = (_countDown--);
return result;
}
I'm asking as well, since I want to do something similar but with different Fontsizes, so it would be great to make this work with a automatich height/width.
Am I doing something horrible wrong here?