wpfteleriktelerik-gridradgridview

WPF RadGridView - If Enter Key (But Value Not Changed) Act Like Escape Key


When editing a cell in a RadGridView, the normal behavior for the escape key is to leave edit mode but retain focus on the same cell; if the enter key is pressed, to commit the edit and advance focus to the next editable cell.

My boss would like for me to modify the behavior so that if enter is pressed but the cell's value has not changed, to act as if it were the escape key instead. While I have been able to cancel the commit, but the focus still advances to the next editable cell, and that's not what he wants.

What is the best way to achieve what we're looking for? Thanks in advance for your help.


Solution

  • The easiest approach would probably be to handle the PreviewKeyDown event for the edit TextBox and programmatically commit the edit and do noting else:

    private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            e.Handled = true;
            outerGrid.CommitEdit();
        }
    }
    

    XAML:

    <telerik:GridViewDataColumn>
        <telerik:GridViewDataColumn.CellTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}" />
            </DataTemplate>
        </telerik:GridViewDataColumn.CellTemplate>
        <telerik:GridViewDataColumn.CellEditTemplate>
            <DataTemplate>
                <TextBox Text="{Binding Name}" PreviewKeyDown="TextBox_PreviewKeyDown" />
            </DataTemplate>
        </telerik:GridViewDataColumn.CellEditTemplate>
    </telerik:GridViewDataColumn>
    

    You could of course create a custom GridViewDataColumn class where you implement this behaviour:

    public class CustomColumn : GridViewDataColumn
    {
        public override FrameworkElement CreateCellEditElement(GridViewCell cell, object dataItem)
        {
            TextBox textBox = base.CreateCellEditElement(cell, dataItem) as TextBox;
            textBox.PreviewKeyDown += (s, e) =>
            {
                if (e.Key == Key.Enter)
                {
                    e.Handled = true;
                    DataControl.CommitEdit();
                }
            };
            return textBox;
        }
    }
    

    Usage:

    <telerik:RadGridView.Columns>
        <local:CustomColumn DataMemberBinding="{Binding Name}" Header="Name" />
    </telerik:RadGridView.Columns>