Actual WPF Control 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 actual width of the label, I thought

theLabel.ActualWidth

would do the trick, but after trying this code:

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

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

Thanks.

+5
source share
1 answer

ActualWidth It is not set until the parent elements (and possible children) are laid out.

ActualWidth, . Loaded, , .

+12

All Articles