WPF 控制实际大小
我有这段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>
在后面的代码中,我试图获取标签的实际宽度,我认为
theLabel.ActualWidth
可以解决这个问题,但是在尝试了这段代码之后:
public Window1()
{
InitializeComponent();
double width = theLabel.ActualWidth;
}
宽度的值为0,我还检查了theLabel。 Width,返回 NaN,theLabel.DesiredSize.Width,也返回 0。我可以用什么来查找标签的真实宽度?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在布局组件的父级(以及可能的子级)之前,不会设置
ActualWidth
。要获取组件的
ActualWidth
,您需要等待布局传递完成。 监听 Loaded 事件,作为其直到第一次布局传递之后才调用。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.