0

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?

Community
  • 1
  • 1
Matthias Müller
  • 3,336
  • 3
  • 33
  • 65
  • 1
    `Am I doing something horrible wrong here?` - Yes, you're manipulating UI elements in procedural code, instead of using proper XAML and DataBinding. – Federico Berasategui Jul 01 '14 at 20:35
  • I'm quite sure I'm not the first person in the world who wants to add dynamically a Control and set it in the Middle. – Matthias Müller Jul 02 '14 at 12:23
  • 1
    If you need to "dynamically add" stuff, either use a `ContentPresenter` or an `ItemsControl` and proper DataBinding. WPF is not winforms. Don't create or manipulate UI elements in procedural code, that's what XAML is for. – Federico Berasategui Jul 02 '14 at 14:34

0 Answers0