65

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

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

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

4

4 回答 4

89

您可以使用我刚刚编写的这个小辅助函数,它将检查给定容器中的元素是否对用户可见。true如果元素部分可见,则该函数返回。如果要检查它是否完全可见,请将最后一行替换为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您的 Window.

于 2009-10-05T00:40:18.803 回答
19
public static bool IsUserVisible(this UIElement element)
{
    if (!element.IsVisible)
        return false;
    var container = VisualTreeHelper.GetParent(element) as FrameworkElement;
    if (container == null) throw new ArgumentNullException("container");

    Rect bounds = element.TransformToAncestor(container).TransformBounds(new Rect(0.0, 0.0, element.RenderSize.Width, element.RenderSize.Height));
    Rect rect = new Rect(0.0, 0.0, container.ActualWidth, container.ActualHeight);
    return rect.IntersectsWith(bounds);
}
于 2014-01-28T17:04:28.193 回答
7

接受的答案(以及此页面上的其他答案)解决了原始发布者遇到的具体问题,但他们没有对标题中写的问题给出充分的答案,即如何确定控件是否对用户. 问题是被其他控件覆盖的控件是不可见的,即使它可以呈现并且它位于其容器的边界内,这是其他答案正在解决的问题。

要确定某个控件是否对用户可见,您有时必须能够确定 WPF UIElement 是否可由用户单击(或在 PC 上鼠标可访问)

当我试图检查一个按钮是否可以被用户单击鼠标时,我遇到了这个问题。一个困扰我的特殊情况是,一个按钮实际上对用户可见,但覆盖有一些透明(或半透明或完全不透明)层,以防止鼠标点击。在这种情况下,控件可能对用户可见,但用户无法访问,这有点像它根本不可见。

所以我不得不想出我自己的解决方案。

编辑- 我原来的帖子有一个使用 InputHitTest 方法的不同解决方案。然而,它在很多情况下都不起作用,我不得不重新设计它。这个解决方案更加健壮,并且似乎运行良好,没有任何假阴性或阳性。

解决方案:

  1. 获取对象相对于应用程序主窗口的绝对位置
  2. 呼叫VisualTreeHelper.HitTest所有角落(左上、左下、右上、右下)
  3. 如果从对象获得的所有角都等于原始对象或其可视父对象,则我们称该对象为完全可点击对象,而对于一个或多个角,我们称其为部分可点击对象。VisualTreeHelper.HitTest

请注意#1:这里对完全可点击或部分可点击的定义并不准确——我们只是检查对象的所有四个角都是可点击的。例如,如果一个按钮有 4 个可点击的角,但它的中心有一个不可点击的点,我们仍将其视为完全可点击。检查给定对象中的所有点太浪费了。

请注意 #2:如果我们希望找到它,有时需要将对象IsHitTestVisible 属性设置为true(但是,这是许多常见控件的默认值)VisualTreeHelper.HitTest

    private bool isElementClickable<T>(UIElement container, UIElement element, out bool isPartiallyClickable)
    {
        isPartiallyClickable = false;
        Rect pos = GetAbsolutePlacement((FrameworkElement)container, (FrameworkElement)element);
        bool isTopLeftClickable = GetIsPointClickable<T>(container, element, new Point(pos.TopLeft.X + 1,pos.TopLeft.Y+1));
        bool isBottomLeftClickable = GetIsPointClickable<T>(container, element, new Point(pos.BottomLeft.X + 1, pos.BottomLeft.Y - 1));
        bool isTopRightClickable = GetIsPointClickable<T>(container, element, new Point(pos.TopRight.X - 1, pos.TopRight.Y + 1));
        bool isBottomRightClickable = GetIsPointClickable<T>(container, element, new Point(pos.BottomRight.X - 1, pos.BottomRight.Y - 1));

        if (isTopLeftClickable || isBottomLeftClickable || isTopRightClickable || isBottomRightClickable)
        {
            isPartiallyClickable = true;
        }

        return isTopLeftClickable && isBottomLeftClickable && isTopRightClickable && isBottomRightClickable; // return if element is fully clickable
    }

    private bool GetIsPointClickable<T>(UIElement container, UIElement element, Point p) 
    {
        DependencyObject hitTestResult = HitTest< T>(p, container);
        if (null != hitTestResult)
        {
            return isElementChildOfElement(element, hitTestResult);
        }
        return false;
    }               

    private DependencyObject HitTest<T>(Point p, UIElement container)
    {                       
        PointHitTestParameters parameter = new PointHitTestParameters(p);
        DependencyObject hitTestResult = null;

        HitTestResultCallback resultCallback = (result) =>
        {
           UIElement elemCandidateResult = result.VisualHit as UIElement;
            // result can be collapsed! Even though documentation indicates otherwise
            if (null != elemCandidateResult && elemCandidateResult.Visibility == Visibility.Visible) 
            {
                hitTestResult = result.VisualHit;
                return HitTestResultBehavior.Stop;
            }

            return HitTestResultBehavior.Continue;
        };

        HitTestFilterCallback filterCallBack = (potentialHitTestTarget) =>
        {
            if (potentialHitTestTarget is T)
            {
                hitTestResult = potentialHitTestTarget;
                return HitTestFilterBehavior.Stop;
            }

            return HitTestFilterBehavior.Continue;
        };

        VisualTreeHelper.HitTest(container, filterCallBack, resultCallback, parameter);
        return hitTestResult;
    }         

    private bool isElementChildOfElement(DependencyObject child, DependencyObject parent)
    {
        if (child.GetHashCode() == parent.GetHashCode())
            return true;
        IEnumerable<DependencyObject> elemList = FindVisualChildren<DependencyObject>((DependencyObject)parent);
        foreach (DependencyObject obj in elemList)
        {
            if (obj.GetHashCode() == child.GetHashCode())
                return true;
        }
        return false;
    }

    private IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
    {
        if (depObj != null)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                if (child != null && child is T)
                {
                    yield return (T)child;
                }

                foreach (T childOfChild in FindVisualChildren<T>(child))
                {
                    yield return childOfChild;
                }
            }
        }
    }

    private Rect GetAbsolutePlacement(FrameworkElement container, FrameworkElement element, bool relativeToScreen = false)
    {
        var absolutePos = element.PointToScreen(new System.Windows.Point(0, 0));
        if (relativeToScreen)
        {
            return new Rect(absolutePos.X, absolutePos.Y, element.ActualWidth, element.ActualHeight);
       }
        var posMW = container.PointToScreen(new System.Windows.Point(0, 0));
        absolutePos = new System.Windows.Point(absolutePos.X - posMW.X, absolutePos.Y - posMW.Y);
        return new Rect(absolutePos.X, absolutePos.Y, element.ActualWidth, element.ActualHeight);
   }

然后,要确定一个按钮(例如)是否可点击,只需调用:

 if (isElementClickable<Button>(Application.Current.MainWindow, myButton, out isPartiallyClickable))
 {
      // Whatever
 }
于 2017-02-15T16:28:35.597 回答
5

将这些属性用于包含控件:

VirtualizingStackPanel.IsVirtualizing="True" 
VirtualizingStackPanel.VirtualizationMode="Recycling"

然后像这样连接收听您的数据项的 INotifyPropertyChanged.PropertyChanged 订阅者

    public event PropertyChangedEventHandler PropertyChanged
    {
        add
        {
            Console.WriteLine(
               "WPF is listening my property changes so I must be visible");
        }
        remove
        {
            Console.WriteLine("WPF unsubscribed so I must be out of sight");
        }
    }

有关更多详细信息,请参阅: http://joew.spaces.live.com/?_c11_BlogPart_BlogPart=blogview&_c=BlogPart&partqs= cat%3DWPF

于 2009-12-04T10:20:15.210 回答