Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Control actual size

I have this piece of XAML code:

<Window x:Class="SizingTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Label x:Name="theLabel" Width="Auto">A very large label with a lot of text</Label>
    </Grid>
</Window>

In the code behind, I'm trying to get the label's actual width, I thought

theLabel.ActualWidth

would do the trick, but after trying this code:

public Window1()
{
    InitializeComponent();
    double width = theLabel.ActualWidth;
}

The value of width is 0, I also checked with theLabel.Width, which returns NaN, theLabel.DesiredSize.Width, which also return 0. What can I use to find the real width of the label?

Thank you.

like image 872
Carlo Avatar asked Jul 16 '09 01:07

Carlo


1 Answers

ActualWidth isn't set until the component's parents (and possible children) are laid out.

To get a component's ActualWidth, you'll need to wait for a layout pass to complete. Listen to the Loaded event, as its not called until after the first layout pass.

like image 111
Kevin Montrose Avatar answered Sep 18 '22 22:09

Kevin Montrose