【问题标题】:Get height and width of UIElement?获取 UIElement 的高度和宽度?
【发布时间】:2012-10-10 20:50:59
【问题描述】:

我目前创建了一个继承自 Popup 的类。

最后,它将用于在编辑时向用户显示带有验证规则的弹出窗口,例如 TextBox

因此,到目前为止,我使用此构造函数创建了 ValidationPopup:

public ValidationPopup(UIElement parent, double width) : base()
{
   this.parent = parent;
   this.width = width;
   InitControl();
}

我想将弹出窗口的大小设置为与 PlacementTarget 父级的大小相等。 为了让许多不同的控件能够拥有这些 ValidationPopups 之一,我将 UIElement 作为父级传递,而不是 TextBox 等。 我的问题是我必须在构建 ValidationPopup 实例时传递此控件的宽度和高度值才能正确调整其大小。

是否可以从UIElement 获取这些值? 我在 MSDN 上看到了 RenderSize,但它只给了我 0.0 的宽度和高度值。

这是我设置 ValidationPopup 的一个实例:

txtOperator = new TextBox();
layoutGrid.Children.Add(txtOperator);
operatorVPU = new ValidationPopup(txtOperator, txtOperator.Width);

我尝试使用 RenderSize,但这在整个 UI 完成之前不起作用。

此时有没有办法获取 UIElement 的高度和宽度值? 是否有其他更好的方法可以达到同样的效果?

【问题讨论】:

    标签: c# wpf height width uielement


    【解决方案1】:

    听起来您需要使用ActualWidth/Height 属性。如果它们仍然是 0 或 NaN,您可以尝试在视图创建的稍后部分执行此代码。

    【讨论】:

    • 实际上没有 AcutalHeight/Width 属性,但在搜索时我发现 FrameworkElement 的 Width 和 Height 属性从属于 UIElement,可以代替 UIElement 使用,但结果相同 :)
    • 嗯好吧 FrameworkElement 的 Height 属性也是 NaN。你的建议是对的。现在我使用 ActualHeight。
    猜你喜欢
    • 2017-12-26
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多