在WPF中获取可见的控件大小

我有一个没有完全显示的控件(通过减小窗口大小)。 但是此控件的ActualWidth和RenderSize / DesiredSize仍然显示它的总大小。 我编写了下一个代码,但它忽略了窗口的滚动条宽度并且看起来很难看。 也许有办法以更优雅的方式获得可见的控制尺寸?

private static double GetVisibleWidth(UIElement element, FrameworkElement container) { var visibleBounds = element.TransformToAncestor(container) .TransformBounds(new Rect(new Point(0, 0), element.RenderSize)); double visibleWidth = element.RenderSize.Width; if (container != null) { visibleWidth = Math.Min(container.ActualWidth - visibleBounds.X, visibleWidth); } return visibleWidth; } 

我说的是什么尺寸

LayoutInformation.GetLayoutClip可能就是您所需要的。

返回表示元素可见区域的Geometry。

但请注意,如果element.IsArrangeValid && element.IsMeasureValid == false ,则返回null 。 这是您可以使用的方法:

 private Size GetVisibleSize(FrameworkElement element) { Rect? bounds = LayoutInformation.GetLayoutClip(element)?.Bounds; if (bounds == null) { return new Size(element.ActualWidth, element.ActualHeight); } return new Size(bounds.Value.Width, bounds.Value.Height); } 

当你的元素在scrollviewer中时,这不起作用,因为它在技术上没有被剪裁。