在 WPF 中,如何确定控件是否对用户可见? [英] In WPF, how can I determine whether a control is visible to the user?

查看:36
本文介绍了在 WPF 中,如何确定控件是否对用户可见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在展示一棵很大的树,里面有很多东西.这些项目中的每一个都通过其关联的 UserControl 控件向用户显示信息,并且这些信息必须每 250 毫秒更新一次,这可能是一项非常昂贵的任务,因为我还使用反射来访问它们的某些值.我的第一种方法是使用 IsVisible 属性,但它没有按我预期的那样工作.

I'm displaying a very big tree with a lot of items in it. Each of these items shows information to the user through its associated UserControl control, and this information has to be updated every 250 milliseconds, which can be a very expensive task since I'm also using reflection to access to some of their values. My first approach was to use the IsVisible property, but it doesn't work as I expected.

有什么方法可以确定控件对用户是否可见"?

Is there any way I could determine whether a control is 'visible' to the user?

注意:我已经在使用 IsExpanded 属性来跳过更新折叠节点,但有些节点有 100 多个元素,无法找到跳过网格视口之外的元素的方法.

Note: I'm already using the IsExpanded property to skip updating collapsed nodes, but some nodes have 100+ elements and can't find a way to skip those which are outside the grid viewport.

推荐答案

您可以使用我刚刚编写的这个小辅助函数,该函数将检查给定容器中的元素是否对用户可见.如果元素部分可见,该函数返回 true.如果要检查它是否完全可见,请将最后一行替换为 rect.Contains(bounds).

You can use this little helper function I just wrote that will check if an element is visible for the user, in a given container. The function returns true if the element is partly visible. If you want to check if it's fully visible, replace the last line by rect.Contains(bounds).

private bool IsUserVisible(FrameworkElement element, FrameworkElement container)
{
    if (!element.IsVisible)
        return false;

    Rect bounds = element.TransformToAncestor(container).TransformBounds(new Rect(0.0, 0.0, element.ActualWidth, element.ActualHeight));
    Rect rect = new Rect(0.0, 0.0, container.ActualWidth, container.ActualHeight);
    return rect.Contains(bounds.TopLeft) || rect.Contains(bounds.BottomRight);
}

在您的情况下,element 将是您的用户控件,而 container 将是您的窗口.

In your case, element will be your user control, and container your Window.

这篇关于在 WPF 中,如何确定控件是否对用户可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆