Q:

How to prevent deselection in a WPF DataGrid?

I want that at any given moment some row is selected in a DataGrid. I don't want it to allow deselection. How to achieve that?

A:

XAML
<DataGrid SelectionMode="Single" SelectionChanged="DataGrid_SelectionChanged">
    ...           
</DataGrid>

C#
private void DataGrid_SelectionChanged(
    object sender,
    SelectionChangedEventArgs e)
{
    DataGrid g = sender as DataGrid;
    if (g != null &&
        e.AddedItems.Count == 0 &&
        e.RemovedItems.Count > 0)
    {
        this.Dispatcher.BeginInvoke((ThreadStart)delegate
        {
            g.SelectedItem = (Device)e.RemovedItems[0];
        });
    }
}

