我有一个控件没有完全显示(通过减小窗口大小)。 但是这个控件的 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
可能是您需要的。
Returns a Geometry that represents the visible region of an element.
但请注意,如果 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);
}
当您的元素在滚动查看器中时,这将不起作用,因为它在技术上没有被剪裁。
关于c# - 在 WPF 中获取控件的可见大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36926571/