首页 文章

LogicalTree Control直接在鼠标下没有VisualTree

提问于
浏览
0

这是一个WPF应用程序 .

我试图直接在鼠标下控制它,这被证明是一个令人惊讶的痛苦 .

Mouse.DirectlyOver,InputHitTest和VisualTreeHelper.HitTest都引用了VISUAL树 . 我正试图 grab 控制本身 .

示例:如果我有一个TextBox并使用上述任何一个,它将返回一个TextBoxView,而我想要TextBox本身 .

这发生在PreviewLeftButtonDown事件中 . 发件人不是一个选项,因为Sender始终是我的ListViewItem . 如果我检查e.OriginalSource它仍然是VisualTree元素而不是实际控件 .

如果需要,很高兴进一步解释 .

谢谢

3 回答

  • 1

    我同意mdm20,到达 Textbox 的唯一方法是遍历父母 . 事实上,here is a link to the same question asked a couple of years ago,答案相同 . 如果你想限制不必要的树遍历,那么一旦你点击 ListViewItem 就可以停止搜索,因为无论如何,高于该点的任何东西都不是你想要的 .

    但是,添加最后一个链接和this one together,在我看来你已经有了答案 . 如果返回了 TextBoxView ,那么您就知道文本框已被命中 . 你甚至可以缓存传入 HitTestFilterCallBack 的潜在的 TextBox ,但这更像是一个理论,可能容易出错 . 但是,沿着那条路走,你可以测试通过过滤器的 TextBox 是否是 TextBoxView 的父级

  • 1

    您只需沿着可视树向上走,直到找到所需的类型 . 这是一些代码的link .

    这是该链接的代码

    // walk up the visual tree to find object of type T, starting from initial object
    public static T FindUpVisualTree<T>(DependencyObject initial) where T : DependencyObject
    {
        DependencyObject current = initial;
    
        while (current != null && current.GetType() != typeof(T))
        {
             current = VisualTreeHelper.GetParent(current);
        }
        return current as T;   
    }
    
  • 4

    走上可视树,直到找到 UIElement

    public UIElement FindUIElement(DependencyObject visualTreeNode)
    {
        UIElement elem;
        while ((elem = (visualTreeNode as UIElement)) != null)
            visualTreeNode = VisualTreeHelper.GetParent(visualTreeNode);
        return elem;
    }
    

相关问题