According to my researches, attached behavior is the only acceptable solution for me. Hope this will help somebody more:
public class DataGridBehavior
{
public static readonly DependencyProperty IsDeselectOnLostFocusProperty =
DependencyProperty.RegisterAttached("IsDeselectOnLostFocus", typeof(bool), typeof(DataGridBehavior), new UIPropertyMetadata(false, PropertyChangedCallback));
private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var dg = dependencyObject as DataGrid;
if (dg == null)
return;
if (e.NewValue is bool == false)
return;
if ((bool)e.NewValue)
dg.LostFocus += dg_LostFocus;
}
static void dg_LostFocus(object sender, RoutedEventArgs e)
{
(sender as DataGrid).SelectedIndex = -1;
}
public static bool GetIsDeselectOnLostFocus(DataGrid dg)
{
return(bool)dg.GetValue(IsDeselectOnLostFocusProperty);
}
public static void SetIsDeselectOnLostFocus(DataGrid dg, bool value)
{
dg.SetValue(IsDeselectOnLostFocusProperty, value);
}
}
Then:
<Style TargetType="{x:Type DataGrid}">
<Setter Property="helpers:DataGridBehavior.IsDeselectOnLostFocus" Value="True"/>
</Style>