Reputation: 6911
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.
Upvotes: 12
Views: 29396
Reputation: 347
Are you actually looking to clear selected rows/cells?
My understanding was that you wanted to clear the entire DataGrid
.
If so, you could do this:
myDataGrid.ItemsSource = null;
Upvotes: 0
Reputation: 14037
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
Upvotes: 5