如何在运行时获取 WPF 元素的尺寸而不在编译时指定它们
问题?
<UI:PanelBrowser Margin="12,27,12,32"></UI:PanelBrowser>
WPF 很荒谬,因为在这种情况下不手动指定属性(例如宽度和高度)会导致它们具有值 Doulbe.NaN
。问题是我需要知道这个数字。我不会在 XAML 中手动设置宽度和高度,因为这会阻止其调整大小。
给定上面的 XAML 片段(该对象是 Border 控件的简单子类),如何在运行时获取 Width 和 Height 属性的值?
编辑:
哇,我觉得很可笑。我读到了关于 ActualWidth 和 ActualHeight 的内容,但它们始终为我返回 0 和 0。原因是我在框架元素的构造函数中测试了这些属性,然后才实际初始化它们。希望这可以帮助遇到同样问题并测试谬误的人。 :)
The problem?
<UI:PanelBrowser Margin="12,27,12,32"></UI:PanelBrowser>
WPF is ridiculous in that not manually specifying properties (Such as Width and Height) in this case causes them to have the values Doulbe.NaN
. The problem is that I need to know this number. I'm not going to manually set a width and height in the XAML because that stops it from resizing.
Given the above piece of XAML (this object is a simple subclass of the Border control), how can I get the values of the Width and Height properties at run-time?
Edit :
Wow, I feel ridiculous. I read about ActualWidth
and ActualHeight
, but they were consistently returning 0 and 0 for me. The reason is that I was testing for these properties in the constructor of the Framework Element, before they were actually initialized. Hope this helps someone who runs into the same issue and testing fallacies. :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试使用 FrameworkElement.ActualWidth 和 ActualHeight 属性。
Try using the FrameworkElement.ActualWidth and ActualHeight properties, instead.
WPF FrameworkElement 类为此提供了两个 DependencyProperties:
FrameworkElement.ActualWidth
和FrameworkElement.ActualHeight
将在运行时获取呈现的宽度和高度。The WPF FrameworkElement class provides two DependencyProperties for that purpose:
FrameworkElement.ActualWidth
andFrameworkElement.ActualHeight
will get the rendered width and height at run-time.您可以使用元素的
ActualWidth
和ActualHeight
属性来获取绘制元素时的宽度和高度值。You can use elements'
ActualWidth
andActualHeight
properties to get the values of the width and height when they were drawn.使用VisualTreeHelper.GetDescendantBounds(Visual Reference),它返回矩形。
然后检查矩形的高度。
例如)
或
使用UIElement.Measure(Size size),它会将Size分配给DesiredSize。
例如)
Use VisualTreeHelper.GetDescendantBounds(Visual Reference), and it return Rect.
Then Check the height of the Rect.
Ex)
OR
Use UIElement.Measure(Size size), it will assign the Size into DesiredSize.
Ex)