Ensuring ActualWidth does not equal 0 in WPF

4k Views Asked by At

So I've read that ActualWidth may equal 0 until it is fully loaded. I added its event handler, like so, to make sure it's fully loaded:

text.AddHandler(TextBlock.LoadedEvent, new RoutedEventHandler(textBlock_Loaded));

In the textBlock_Loaded event, I have:

TextBlock tb = sender as TextBlock;
textBlockWidth = tb.ActualWidth;

I need to use the variable textBlockWidth in my main method, but everytime I write the value of textBlockWidth to output in my Main method, I get 0.

So this question is, how do I ensure that ActualWidth is NOT 0 before performing my actions? Since WPF is event-driven, is there a way I can trigger some method when it's done, instead of before? Otherwise, it'll return 0.

2

There are 2 best solutions below

3
On BEST ANSWER

You won't be able to get the ActualWidth. Since, it will not be updated at the time of loaded. So, you should use Dispatcher of the TextBlock or it's Parent to get the ActualWidth or ActualHeight.

this.textBlock.Dispatcher.BeginInvoke((Action)(() =>
            {
                textBlock = this.textBlock.ActualWidth;
            }));
6
On

Why store the actual width? Why not store a reference to the control and get the actual width when you really need it?

Having said that I don't see why your code is failing as using the loaded event should be good enough. According to the Object Lifetime Events MSDN page:

The Loaded event is raised before the final rendering, but after the layout system has calculated all necessary values for rendering.

So all the controls should have their final position and size values set. Also:

the Loaded event is raised as a coordinated effort throughout the entire element tree (specifically, the logical tree). When all elements in the tree are in a state where they are considered loaded, the Loaded event is first raised on the root element. The Loaded event is then raised successively on each child element.