Reputation: 725
I'm using a DataGrid in cell edit mode. I want to deselect the currently edited cell when clicking outside the cell (the click can be on another cell, another control, on the window, on other grid, anywhere).
I'm using this code, but it works when clicking only on another control (e.g., if I click on the window, it does not trigger):
private void Grid_LostFocus(object sender, RoutedEventArgs e)
{
((DataGrid)sender).UnselectAllCells();
}
How can a DataGrid cell be deselected when clicking anywhere outside it?
Upvotes: 2
Views: 1297
Reputation: 725
Thank you, vishakh369! Based on your answer, I found the solution:
private void sequenceGrid1_MouseLeave(object sender, MouseEventArgs e)
{
PreviewMouseLeftButtonDown += mouseClick;
}
private void mouseClick(object sender, MouseEventArgs e)
{
HitTestResult hitTestResult;
hitTestResult = VisualTreeHelper.HitTest(sequenceGrid1, e.GetPosition(sequenceGrid1));
if (hitTestResult == null) // Click outside the datagrid
{
sequenceGrid1.CommitEdit(DataGridEditingUnit.Row, true);
try
{
sequenceGrid1.Items.Refresh(); // Edit mode still open if there is invalid input
}
catch { }
}
PreviewMouseLeftButtonDown -= mouseClick;
}
}
Upvotes: 1