You must call DataGrid.UnselectAll asynchronously with BeginInvoke to make it work. For this, I wrote the following attached property:
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 created this blog post in creating my solution.
source share