确定用户何时在数据网格内部而不是在行上单击

时间:2016-08-06 03:36:27

标签: wpf datagrid

我正在尝试编写一个像下面这样的简单方法,如果用户点击了数据网格而不是一行,则条件成立。

我只能找到有关如何使用datagridview执行此操作的信息,但wpf数据网格似乎没有相同的功能。

    private void dataGrid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        Point where = new Point();
        var ht = dataGrid.InputHitTest(where);

        if (ht.)
        {
            //clicked on grey area
        }
    }

1 个答案:

答案 0 :(得分:1)

<DataGrid UIElement.PreviewMouseLeftButtonDown="DataGrid_PreviewMouseLeftButtonDown" ... >

代码:

private void DataGrid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine(e.OriginalSource.ToString());
        DependencyObject parent = VisualTreeHelper.GetParent((Visual)e.OriginalSource);
        while (parent as DataGrid == null && parent as DataGridRow == null)
        { 
            parent = VisualTreeHelper.GetParent(parent);
        }
        if (parent as DataGrid != null)
            MessageBox.Show("Clicked inside DataGrid");
        else if (parent as DataGridRow != null)
            MessageBox.Show("Clicked inside DataGridRow");
    }