3
votes

I've a DataGrid in WPF looks as the following:

DataGrod rows

The DataGrid's rows above, represents the following sample model:

    class MyModel
    {
        public string Value { get; set; }
        public string Message { get; set; }
    }

I want to prevent the auto selection changing when i press enter key after editing the textbox, So instead of moving to the second row when editing the first row textbox content, the label on the right will be updated after some conditions ex: Text ok if text contains only digits chars, and error otherwise.

how can i do this?

I tried doing this by playing with the code behind of my view KeyPressed, PreviewKeyDown and LostFocus events as the following but it doesn't work :(

    if (e.Key == Key.Enter || e.Key == Key.Return)
    {
        var dataGrid = (DataGrid) sender;
        if (dataGrid != null)
        {
            var row = dataGrid.ItemContainerGenerator.ContainerFromItem(dataGrid.SelectedItem) as DataGridRow;
            base.OnPreviewKeyDown(e);
            //e.Handled = true;
            if (row != null)
                dataGrid.SelectedItem = row.Item;
        }
    else
        base.OnPreviewKeyDown(e);
    }
1

1 Answers

3
votes

Try this change.

//base.OnPreviewKeyDown(e);
e.Handled = true;