Cristian M
Cristian M

Reputation: 725

How to deselect DataGrid cell?

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

Answers (3)

Cristian M
Cristian M

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

ViVi
ViVi

Reputation: 4464

Did you try the MouseLeave event? It should work.

Upvotes: 1

ahmed
ahmed

Reputation: 7

can you try this answer wpf data grid selection

Upvotes: 0

Related Questions