取消选择wpf datagrid中的行

Rob*_*ben 3 wpf binding double-click wpf-controls wpfdatagrid

我有

<DataGrid Name="grid" MouseDoubleClick="Attributes_MouseDoubleClick" >
Run Code Online (Sandbox Code Playgroud)

每当Click Data事件发生在Datagrid行以外的任何其他位置时,我都需要取消选择一行.

grid.CurrentItemnull

我需要火双击事件在一排.但是,问题是,一旦我选择一行并双击网格上的其他位置(标题,空滚动查看区域等),双击事件将按预期触发,但CurrentItem有时是选定的行,有时为null.

为了防止这种行为..我需要取消选择所选行.

关于我应该怎么做的任何想法?

谢谢.

Zam*_*oni 5

您可以在事件源的Visual Tree中搜索DataGridRow类型的实例,以确定是否双击某行或其他位置.

以下站点检测WPF DataGrid上的双击事件包含很好的示例.
我已在此处包含代码,以防网站不再可用.

这是双击的事件处理程序:

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;
}
Run Code Online (Sandbox Code Playgroud)

以下是帮助搜索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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)