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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3878528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:12:15  来源:igfitidea点击:

WPF DataGrid: How to clear selection programmatically?

wpfdatagridselectionclear

提问by newman

How would one just clear it?

一个人怎么会清除它?

There is UnselectAllor UnselectAllCellsmethods, but they don't work. Also, setting SelectedItem = nullor SelectedIndex = -1does not work either.

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

Also I do not want to completely disable the selection, I just want to clear the current selection (if any) and set a new selection programmatically.

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

回答by Evalds Urtans

dataGrid.UnselectAll()

For rows mode

对于行模式

回答by vortexwolf

To clear current selection, you can use this code (as you see it is different whether the mode is Single or Extended)

要清除当前选择,您可以使用此代码(如您所见,模式是 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;

To select new items programmatically, use this code:

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

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

回答by Ken Budris

Disabling and reenabling the DataGrid worked for me.

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

回答by Dunc

DataGrid.UnselectAllCells()

It works for me.

这个对我有用。