加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 22:30:20 所属栏目:百科 来源:网络整理
导读:我有一个没有完全显示的控件(通过减小窗口大小). 但是此控件的ActualWidth和RenderSize / DesiredSize仍然显示它的总大小. 我编写了下一个代码,但它忽略了窗口的滚动条宽度并且看起来很难看. 也许有办法以更优雅的方式获得可见的控制尺寸? private static d
我有一个没有完全显示的控件(通过减小窗口大小).
但是此控件的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.

但请注意,如果元素.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中时,这不起作用,因为它在技术上没有被剪裁.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读