WPF控制实际大小

Car*_*rlo 5 size wpf wpf-controls

我有这段XAML代码:

<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>
Run Code Online (Sandbox Code Playgroud)

我想,在后面的代码中,我试图获得标签的实际宽度

theLabel.ActualWidth
Run Code Online (Sandbox Code Playgroud)

会做的伎俩,但尝试此代码后:

public Window1()
{
    InitializeComponent();
    double width = theLabel.ActualWidth;
}
Run Code Online (Sandbox Code Playgroud)

width的值为0,我还检查了Label.Width,它返回NaN,theLabel.DesiredSize.Width,它也返回0.我可以用什么来查找标签的实际宽度?

谢谢.

Kev*_*ose 12

ActualWidth 在组件的父项(和可能的子项)布局之前,不会设置.

要获得组件ActualWidth,您需要等待布局传递完成.收听Loaded事件,直到第一次布局传递后才调用它.