I have a wpf datagrid bound to a TrackableCollection. In some rare occations, and for only a few selected users, the application will crash when the user adds a new record by en
The problem is related to a bug in DataGridAutomationPeer.RaiseAutomationSelectionEvents
internal method which simply speaking does not check if SelectedItem property is null or not. It can easily be reproduced by running "Microsoft Narrator" tool in Windows 7.
Because this is a sealed class there is no easy way to fix it except intercepting this method using Reflection.Emit or any mocking tool out there and even if it's fixed we have no guarantee that Microsoft won't change this method name, signature or behaviour.
I implemented a "good enough" fix by inheriting from DataGrid which will change the way DataGrid is unselected when the SelectedItem is null but only if narrator/touchscreen is present.
Hopefully the bug will be fixed soon. Add reference to UIAutomationProvider if necessary.
using System.Windows.Automation.Peers;
using System.Windows.Controls;
public class TooDataGrid: DataGrid
{
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{
if(AutomationPeer.ListenerExists(AutomationEvents.SelectionItemPatternOnElementSelected) ||
AutomationPeer.ListenerExists(AutomationEvents.SelectionItemPatternOnElementAddedToSelection) ||
AutomationPeer.ListenerExists(AutomationEvents.SelectionItemPatternOnElementRemovedFromSelection))
{
if(SelectedItem == null)
{
return;
}
}
base.OnSelectionChanged(e);
}
}