在WPF中,我怎么能确定控件是否对用户可见?控件、用户、我怎么能、WPF

2023-09-02 10:17:07 作者:白首有我共你

我展示了很多在里面的物品有非常大的树。通过其相关联的用户控件的控件的每个项目显示信息给用户,并且该信息必须被更新每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.

推荐答案

您可以用这个小助手功能,我只是写,将检查元素是否可见对于用户来说,在给定的容器。该函数返回如果元素是若隐若现。如果你想检查它是否是完全可见的,由 rect.Contains替换最后一行(边界)

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);
}

在你的情况,元素将是你的用户控制和容器你的窗口。

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