如何清除选择内容?
有UnselectAll
或UnselectAllCells
方法,但它们无法起作用。另外,设置SelectedItem = null
或SelectedIndex = -1
也不起作用。
此外,我不想完全禁用选择功能,我只想清除当前的选择(如果有),然后以编程方式设置新的选择。
dataGrid.UnselectAll()
对于行模式
要清除当前选择,您可以使用以下代码(如您所见,它在单选和扩展模式下是不同的)
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
DataGrid.UnselectAllCells()
对我来说它有效。
禁用和重新启用DataGrid对我有用。
myDataGrid.ItemsSource = null;
SelectedItems.Clear
或SelectedItem = null
。如果出现新的SelectionMode值,我认为这个if-else应该被重写。 - vortexwolf