UWP 中按钮和单选按钮的 DesiredSize XAML

DesiredSize of a button and radio button in UWP XAML

我需要测量一个按钮(和单选按钮)的 DesiredSize 或 ActualHeight/Width,但实际上没有将它放到可视化树上,但我一直在取回无意义的值。在测量 TextBlock 等其他控件时,同样的方法也适用。

        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 吗?

我猜这是不可能的。您正在按钮加载其模板之前对其进行测量。

我只能建议这样做:

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;
};

但这有点老套,按钮要到稍后才会加载,这使得整个过程异步,这可能难以管理。

I need to measure the DesiredSize or ActualHeight/Width of a button (and radio button) without actually putting it onto the visual tree but I keep getting back non-sense values.

如果你给Button.Content赋一个字符串值,这个值会在运行时通过Binding赋给里面的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;

然后你会得到这个按钮的正确尺寸。