【问题标题】:WPF DataGrid: How to clear selection programmatically?WPF DataGrid:如何以编程方式清除选择?
【发布时间】:2011-04-22 04:01:41
【问题描述】:

如何清除它?

UnselectAllUnselectAllCells 方法,但它们不起作用。此外,设置SelectedItem = nullSelectedIndex = -1 也不起作用。

我也不想完全禁用选择,我只想清除当前选择(如果有)并以编程方式设置新选择。

【问题讨论】:

    标签: wpf datagrid selection


    【解决方案1】:
    dataGrid.UnselectAll()
    

    对于行模式

    【讨论】:

      【解决方案2】:

      要清除当前选择,您可以使用此代码(如您所见,模式是单模式还是扩展模式是不同的)

      if(this.dataGrid1.SelectionUnit != DataGridSelectionUnit.FullRow)
          this.dataGrid1.SelectedCells.Clear();
      
      if (this.dataGrid1.SelectionMode != DataGridSelectionMode.Single) //if the Extended mode
          this.dataGrid1.SelectedItems.Clear();
      else 
          this.dataGrid1.SelectedItem = null;
      

      要以编程方式选择新项目,请使用以下代码:

      if (this.dataGrid1.SelectionMode != DataGridSelectionMode.Single) 
      {    //for example, select first and third items
          var firstItem = this.dataGrid1.ItemsSource.OfType<object>().FirstOrDefault();
          var thirdItem = this.dataGrid1.ItemsSource.OfType<object>().Skip(2).FirstOrDefault();
      
          if(firstItem != null)
              this.dataGrid1.SelectedItems.Add(firstItem);
          if (thirdItem != null)
              this.dataGrid1.SelectedItems.Add(thirdItem);
      }
      else
          this.dataGrid1.SelectedItem = this.dataGrid1.ItemsSource.OfType<object>().FirstOrDefault(); //the first item
      

      【讨论】:

      • @miliu 是的,我之前的代码不正确。我修正了我的答案。
      • @vortex:我不知道我是不是做错了什么,但是这个用于清除选择的新代码对我也不起作用。我在 MouseDoubleClick 事件中使用此代码。
      • 就我而言,我找到了一种解决方法:当我通过调用“Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => grid.Items.Refresh() ));"
      • 请注意...WPF DataGrid 很棒,但一些小事让我抓狂。
      • @GeorgeBirbilis 我的答案是很久以前的,我不记得了。但是我的代码有 if-else 组合,根据选择模式使用SelectedItems.ClearSelectedItem = null。如果出现新的 SelectionMode 值,我认为应该重写这个 if-else。
      【解决方案3】:
      DataGrid.UnselectAllCells()
      

      它对我有用。

      【讨论】:

        【解决方案4】:

        禁用和重新启用 DataGrid 对我有用。

        【讨论】:

          【解决方案5】:

          您是否真的要清除选定行/单元格? 我的理解是你想清除整个DataGrid。 如果是这样,您可以这样做:

          myDataGrid.ItemsSource = null;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-10-23
            • 1970-01-01
            • 2023-03-06
            • 1970-01-01
            • 1970-01-01
            • 2021-03-15
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多