unselect row in wpf datagrid

被刻印的时光 ゝ 提交于 2019-11-29 15:48:06

You can search the Visual Tree of the event source for an instance of type DataGridRow to determine if you double clicked on a row or somewhere else.

The following site Detecting Double Click Events on the WPF DataGrid contains good example.
I've include the code here in case the site is no longer available.

Here is the event handler for double click:

private void DataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
  //search the object hierarchy for a datagrid row
  DependencyObject source = (DependencyObject)e.OriginalSource;
  var row = DataGridTextBox.Helpers.UIHelpers.TryFindParent<DataGridRow>(source);

  //the user did not click on a row
  if (row == null) return;

  //[insert great code here...]

  e.Handled = true;
}

Here is the code to help search the Visual Tree:

using System.Windows;
using System.Windows.Media;

namespace DataGridTextBox.Helpers
{
  public static class UIHelpers
  {
    public static T TryFindParent<T>(this DependencyObject child) where T : DependencyObject
    {
      //get parent item
      DependencyObject parentObject = GetParentObject(child);

      //we've reached the end of the tree
      if (parentObject == null) return null;

      //check if the parent matches the type we're looking for
      T parent = parentObject as T;
      if (parent != null)
      {
        return parent;
      }
      else
      {
        //use recursion to proceed with next level
        return TryFindParent<T>(parentObject);
      }
    }

    public static DependencyObject GetParentObject(this DependencyObject child)
    {
      if (child == null) return null;

      //handle content elements separately
      ContentElement contentElement = child as ContentElement;
      if (contentElement != null)
      {
        DependencyObject parent = ContentOperations.GetParent(contentElement);
        if (parent != null) return parent;

        FrameworkContentElement fce = contentElement as FrameworkContentElement;
        return fce != null ? fce.Parent : null;
      }

      //also try searching for parent in framework elements (such as DockPanel, etc)
      FrameworkElement frameworkElement = child as FrameworkElement;
      if (frameworkElement != null)
      {
        DependencyObject parent = frameworkElement.Parent;
        if (parent != null) return parent;
      }

      //if it's not a ContentElement/FrameworkElement, rely on VisualTreeHelper
      return VisualTreeHelper.GetParent(child);
    }
  }
}

That event is fired by the grid, not by the row. I mean, is fired when you double-click somewhere in the grid, it could be a row selected or not (or not the row that you spect wich is worse).

You could edit the itemtemplate for each row and include there your double-click event or capture the cordenates from the mouse, but this is a little bit tricky.

Hope helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!