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

标签 c# 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;
    }

What size i am speaking about

最佳答案

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/

相关文章:

c# - Asp.net 图表,如何将 X 轴标签位置设置为左对齐而不是居中?

c# - 如何让 VS2010 不在方法下拉列表中显示无用信息?

wpf - 在 WPF 用户控件上使用非简单类型的依赖属性的模式

c# - Messagebox 多次显示

c# - 如何在 WPF TreeView 中添加和显示图像?

c# - Windows 键的 SendKey 是什么

c# - TouchDevice.Capture() 在 WPF 中实际上做了什么?

c# - 图像未显示在 FlowDocument 中

c# - 我在哪里可以找到 .NET 框架包装的所有 "COR_E_"HRESULT 的引用?

.net - 根据上下文值更改 DataGridCell 的背景颜色。 (WPF)