You have to call DataGrid.UnselectAll asynchronously with BeginInvoke to get it to work. I wrote the following attached property to handle this:
using System;
using System.Windows;
using System.Windows.Threading;
using Microsoft.Windows.Controls;
namespace DataGridNoSelect
{
public static class DataGridAttach
{
public static readonly DependencyProperty IsSelectionEnabledProperty = DependencyProperty.RegisterAttached(
"IsSelectionEnabled", typeof(bool), typeof(DataGridAttach),
new FrameworkPropertyMetadata(true, IsSelectionEnabledChanged));
private static void IsSelectionEnabledChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var grid = (DataGrid) sender;
if ((bool) e.NewValue)
grid.SelectionChanged -= GridSelectionChanged;
else
grid.SelectionChanged += GridSelectionChanged;
}
static void GridSelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
var grid = (DataGrid) sender;
grid.Dispatcher.BeginInvoke(
new Action(() =>
{
grid.SelectionChanged -= GridSelectionChanged;
grid.UnselectAll();
grid.SelectionChanged += GridSelectionChanged;
}),
DispatcherPriority.Normal, null);
}
public static void SetIsSelectionEnabled(DataGrid element, bool value)
{
element.SetValue(IsSelectionEnabledProperty, value);
}
public static bool GetIsSelectionEnabled(DataGrid element)
{
return (bool)element.GetValue(IsSelectionEnabledProperty);
}
}
}
I sourced this blog post in creating my solution.