wpf 获取 UIElement 的高度和宽度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12987814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:51:29  来源:igfitidea点击:

Get height and width of UIElement?

c#wpfheightwidthuielement

提问by TorbenJ

I currently create a class which inherits from a Popup.

我目前创建了一个继承自Popup.

Finally it will be used to show the user a popup with validation rules when editing e.g a TextBox.

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

Therefore I created ValidationPopup with this constructor so far:

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

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

I would like to set the size of the popup equal to the size of the PlacementTarget parent. In order to allow many different controls to be able to have one of these ValidationPopups I pass an UIElementas parent instead of TextBoxetc. My problem is that I have to pass the width and height values of this control when building an instance of ValidationPopup in order to size it properly.

我想将弹出窗口的大小设置为等于 PlacementTarget 父项的大小。为了让许多不同的控件能够拥有这些 ValidationPopup 中的一个,我传递了一个UIElement作为父级而不是TextBox等。我的问题是我必须在构建 ValidationPopup 的实例时传递这个控件的宽度和高度值,以便大小合适。

Is it possible to get these values from UIElement? I saw RenderSize on MSDN but it only gives me 0.0 values for width and height.

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

This is where I setup one instance of ValidationPopup:

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

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

I tried to use RenderSize but this doesn't work until the whole UI is completly finished.

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

Is there a way to get Height and Width values of an UIElement at this point? Are there maybe other even better ways to achieve the same result?

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

采纳答案by Chen Kinnrot

Sounds like you need to use the ActualWidth/Heightproperties. If they are still 0 or NaN, you can try executing this code on a later part of the view creation.

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