如何获取自动调整大小的 WPF 窗口的大小?
我有一个围绕其内容自动调整大小的窗口。对于动画,我需要它的宽度和高度。 ActualWidth
始终是窗口的最大宽度,Width
和 Height
属性表示 NaN。
I have a Window that is autosized around it's content. For an animation I'd need it's width and height. ActualWidth
is always the max width of the window, Width
and Height
properties say NaN.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实际宽度/ActualHeight 将为您提供窗口的实际大小 - 由布局系统,基于窗口的实际渲染。这些应该是您正在寻找的尺寸。然而,计算可能会有轻微的延迟,因为它是基于渲染的,所以如果它们是错误的,我猜它们还没有计算出来 - 并且你会遇到竞争条件。你可以在链接中阅读有关此内容的更多信息上面有一些关于何时计算实际大小的重要注释 - 以及因此 - 为什么它们可以被延迟。
宽度/高度 是请求的尺寸,如果没有明确设置,它们将保留其默认值,即 Double.NaN。
ActualWidth/ActualHeight will give you the actual sizes of the window - given by the layout system, which is based on the actual rendering of the window. These should be the sizes you are looking for. However, there might be a slight delay in the calculation as it is based on rendering, so if they are wrong I guess they aren't calculated yet - and you got a race condition going on.. You can read more about this in links above, where there are some important notes on when the actual sizes are calculated - and hence - why they can be delayed.
Width/Height are requested sizes, and if not set explicitly they will hold their default values, which is Double.NaN.
您可以使用 Window 的 UpdateLayout()-验证
ActualWidth
和ActualHeight
的方法。You can use the Window's UpdateLayout()-Method to have
ActualWidth
andActualHeight
validated.在为尺寸变化设置动画时,只要有可能,您就应该使用 ScaleTransform,而不是更改高度和宽度值。它不仅可以帮助提高性能,而且还可以解决此类问题,因为比例值被指定为百分比,而不是设置您可能不知道的特定大小值。
Whenever possible you should use a
ScaleTransform
instead of changingHeight
andWidth
values when animating a size change. Not only can it help with performance, but it also gets around issues like this since instead of setting a specific size value which you may not know, the scale values are specified as percentages.