UWP XAML中的按钮和单选按钮的DesiredSize
问题描述:
我需要测量按钮(和单选按钮)的DesiredSize或ActualHeight/Width,但实际上并没有将它放到可视化树上,但我总是找回无意义的值。测量其他控件(如TextBlock)时,这种方法也适用。UWP XAML中的按钮和单选按钮的DesiredSize
var button = new Button
{
Content = "Hello World",
FontSize = 15
};
button.Measure(new Size(maxWidth, double.PositiveInfinity));
var height = button.DesiredSize.Height;
var width = button.DesiredSize.Width
我回来了21px的高度和0px的宽度。任何想法,为什么我回到宽度为0?
答
我需要测量一个按钮(和单选按钮)的DesiredSize或ActualHeight/Width,但实际上并没有将它放到可视化树上,但我总是找回无意义的值。
如果指定一个字符串值Button.Content
,该值将通过在运行时,这之后会发生绑定被分配到里面的TextBlock的Button.Measure
(您可以通过添加按钮的页面中看到这一点,并检查LiveProperty Explorer):
所以你得到了错误的期望大小。
作为一种变通方法,您可以创建一个TextBlock和这个TextBlock中分配给按钮:
var tbContent = new TextBlock()
{
Text = "Hello World",
FontSize=15
};
var button = new Button
{
Content = tbContent,
};
var h= button.DesiredSize.Height;
button.Measure(new Size(200, double.PositiveInfinity));
var height = button.DesiredSize.Height;
var width = button.DesiredSize.Width;
然后你会得到这个按钮的正确尺寸。
答
我猜这是不可能的。您在加载模板之前测量按钮。
我只能建议做这样的事情:
var but = new Button();
but.Content = "Hello";
var popup = new Popup();
popup.Child = but;
popup.IsOpen = true;
popup.Visibility = Visibility.Collapsed;
but.Loaded += (s, e) =>
{
System.Diagnostics.Debug.WriteLine(but.RenderSize);
popup.IsOpen = false;
};
但它是一种哈克,按钮将不会加载,直到以后的某个时间,使这可能是难以管理的整个过程异步的。
谢谢埃尔维斯!这样可行! –