Introduction

This sample shows how to recognise the "lost focus" event of a DataGrid, as a whole. The problem with DataGrid.LostFocus is that it is fired with every cell edit. Commonly you may wish to update the database as a whole after the user leaves the DataGrid. This sample shows how to detect the difference.
 

Building the Sample

Just download, unzip, open in Visual Studio and run!
 

Description

The problem with DataGrid.LostFocus is that it is fired with every cell edit.
This is not always a bad thing, as it is useful to process a cell update or register a change of cell.
This is annoyng however, if you want to detect when a user leaves the DataGrid, as a whole, to another control elsewhere on the page.
The solution is to detect what exactly is now in focus, and determine if that is inside or outside the DataGrid.
To do this we can use the FocusManager to get the currently focussed element.
Then we simply check to see if the parent container is part of the DataGrid.
If it is not, we know it is outside the DataGrid and this signifies our DataGrid.LostFocus event.
 
C#
Edit|Remove
private void dg1_LostFocus(object sender, RoutedEventArgs e) 
{ 
    Control ctrl = FocusManager.GetFocusedElement(this) as Control;  
    if (ctrl.Parent != null && ctrl.Parent.GetType() != typeof(DataGridCell)) 
        MessageBox.Show("outside!"); 
}
This sample is in response to a WPF forum question
 

Source Code Files

More Information