How would one just clear it?
There is UnselectAll
or UnselectAllCells
methods, but they don't work. Also, setting SelectedItem = null
or SelectedIndex = -1
does not work either.
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.
DataGrid.UnselectAllCells()
It works for me.
To clear current selection, you can use this code (as you see it is different whether the mode is Single or 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
dataGrid.UnselectAll()
For rows mode
Disabling and reenabling the DataGrid worked for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With