WPF DataGrid:如何以编程方式清除选择?

new*_*man 9 wpf datagrid selection clear

这是另一个网格中的一个简单任务,但我不能在WPF DataGrid中实现它.有UnselectAll或UnselectAllCells方法,但不起作用.此外,设置SelectedItem = null或SelectedIndex = -1也不起作用.

这里有一篇关于完全禁用选择的帖子,但这不是我想要的.我只想清除当前选择(如果有的话)并以编程方式设置新选择.

Eva*_*ans 23

dataGrid.UnselectAll()
Run Code Online (Sandbox Code Playgroud)

对于行模式


vor*_*olf 5

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

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

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

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