简体   繁体   English

DataGrid的C#WPF / XAML预览鼠标事件

[英]C# WPF/XAML Preview Mouse Event for DataGrid

I'm using a WPF DataGrid with c#/xaml in Visual Studio 2013. 我在Visual Studio 2013中使用带有c#/ xaml的WPF DataGrid。

With SelectionMode="Extended", I'm able to multi-select rows in the grid. 使用SelectionMode =“ Extended”,我可以在网格中多选行。

I have a requirement where clicks on one of the columns of the grid are to be ignored relative to row selection. 我有一个要求,相对于行选择,应忽略对网格某一列的单击。

I setup a PreviewMouseLeftButtonDown event that gets called. 我设置了一个被调用的PreviewMouseLeftButtonDown事件。 Since it's a preview event, at the time of the event is processed, the selection in the grid hasn't changed yet. 由于是预览事件,因此在处理事件时,网格中的选择尚未更改。 I'm able to determine the row and column of the click, so I can determine a click has been made in a column that I don't want 我可以确定点击的行和列,因此可以确定在不需要的列中进行了点击

I want to be able to abort the click event at that point so that no change is made to the current selected items in the grid. 我希望能够在那时候中止click事件,以便对网格中的当前选定项目不做任何更改。 Is that possible? 那可能吗?

In the mouse down event I tried something like: 在鼠标按下事件中,我尝试了类似的操作:

    private void GridCtrl_MouseDown(object sender, MouseButtonEventArgs e)
    {
          // ... Other code
          e.Handled = true;
    }

But, despite being marked as handled, it still continues and performs the row selection. 但是,尽管被标记为已处理,它仍然继续并执行行选择。 I also have a 'SelectionChanged' event that I see that it later gets into. 我也有一个'SelectionChanged'事件,后来我发现它进入了。

I think you actually need to handle both tunneling events - one for PreviewLeftMOuseButtonDown and another for PreviewSelectionChanged. 我认为您实际上需要处理两个隧道事件-一个事件用于PreviewLeftMOuseButtonDown,另一个事件用于PreviewSelectionChanged。

My advice is create a flag, let's call it: 我的建议是创建一个标志,我们称之为:

bool _cancelSelectionChange = false;

Then, in your Mouse handler: 然后,在您的鼠标处理程序中:

private void GridCtrl_MouseDown(object sender, MouseButtonEventArgs e)
{
      _cancelSelectionChange = false;

      // ... Other code
      _cancelSelectionChange = true;
      e.Handled = true;
}

Finally, in your selection change handler for the tunneling event: 最后,在您的隧道事件的选择更改处理程序中:

private void GridCtrl_PreviewSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    e.Handled = _cancelSelectionChange;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM