【问题标题】:check if scroll bar is clicked with doubleclick in datagrid检查是否在数据网格中双击滚动条
【发布时间】:2012-01-17 10:44:52
【问题描述】:

我需要我的应用程序在双击 DataGrid 时执行特定操作。如果双击滚动条,则不应执行该操作。所以我试着看看双击了什么:

private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            Point p = Mouse.GetPosition(this.DataGrid1);
            IInputElement ie = this.DataGrid1.InputHitTest(p);
        }

但是当我双击滚动条时,IInputElement 似乎是各种东西: Microsoft.Windows.Themes.ScrollChrome 或 System.Windows.Shapes.Rectangle 。所以我不确定我是否点击了滚动条。

那么如何检查我是否真的双击了滚动条?

【问题讨论】:

    标签: .net wpf datagrid double-click hittest


    【解决方案1】:

    这里不需要使用命中测试,只需通过遍历可视化树检查e.OriginalSource是否有ScrollBar类型的父级即可。这种方法有一个潜在的问题——你的 UI 元素必须被加载,这通常是在处理鼠标事件时的情况。这是检查 UIElement 是否具有特定类型的父级的代码。

    public static T GetParentOfType<T>(DependencyObject current)
              where T : DependencyObject
            {
                for (DependencyObject parent = VisualTreeHelper.GetParent(current);
                    parent != null;
                    parent = VisualTreeHelper.GetParent(parent))
                {
                    T result = parent as T;
    
                    if (result != null)
                        return result;
                }
    
                return null;
            }
    

    【讨论】:

    • 感谢您的回答!顺便说一句,如果我双击一个文本单元格,那么我会在 e.OriginalSource 中获得一个 TextBlock,并且 VisualTreeHelper.GetParent 会为它返回 null。你知道为什么吗?
    • @Bogdan0x400 你传递的是什么类型的 T?
    • 我不使用此代码,我只是在双击一个单元格时尝试 VisualTreeHelper.GetParent(e.OriginalSource) 并返回 null,令我惊讶的是。
    • 它不应该那样做,应该这样。在 WPF 中,Parent 几乎可以设置为任何东西(与 WinForms 相比),它与可视化树没有任何关系(DP 系统非常松散,它是这一事实的实现之一)。你看到这个帖子了吗?其中一个答案建议从上到下采取相反的方式:stackoverflow.com/questions/636383/wpf-ways-to-find-controls
    • 谢谢,我不知道。
    猜你喜欢
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 2011-06-20
    • 2011-09-06
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    相关资源
    最近更新 更多