0
votes

I am a C# novice. I have been trying to capture the value in the datagrid cell that I currently have selected when I press enter and use the value elsewhere. I am currently using a KeyUp event with this handler:

private void Cell_OnKeyUp(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        DataGrid dg = (DataGrid) sender;
        var u = e.OriginalSource as UIElement;
        e.Handled = true;
        u.MoveFocus(new TraversalRequest(FocusNavigationDirection.Up));   
        MyType mo = (MyType) dg.CurrentItem;
        DoSomething(mo);
    }
}

The defualt behavior of the Enter key in a datagrid is to exit editing and move down to the cell below, unless at the bottom of the datagrid.

The handler above works fine except for when I am at the bottom of the datagrid. I end up fetching the value of the cell above...

I have tried some hacks like this:

bool notEnd = u.MoveFocus(new TraversalRequest(FocusNavigationDirection.Down));
if (notEnd)
{
    u.MoveFocus(new TraversalRequest(FocusNavigationDirection.Up));
}   
u.MoveFocus(new TraversalRequest(FocusNavigationDirection.Up));

But then I run into the problem of being unable to make a disticntion between the bottom two cells.

So I guess I have two questions and I am happy with an answer to either:

1. Is there a way to determine when you are in the bottom row of a datagrid?

2. Is there a way to override the default behavior of a pressed enter key in a datagrid?

I would appreciate any suggestions. Thank you.

1
Is there a reason why you use the KeyUp event?phi1010
@phi1010 I was generally unsuccessful with KeyDown (didn't seem to execute my DoSomething() code and at the time, I was in a situation where I was unable to debug... I should probably revisit that with breakpoints) and I saw others using KeyUp! Probably not a great answer/reason.Jon2000lbs
KeyUp in combination with Enter also has some really bad side effects: Imagine a MessageBox showing up while your DataGrid is selected (this might even be from another application). MessageBox-es usually close on KeyDown, so when I press enter on the MessageBox instead of using the mouse, I also trigger your Datagrid action.phi1010
@phi1010 this is also very helpful advice and I really appreciate you putting that scenario on my radar!Jon2000lbs

1 Answers

0
votes

2.: Yes, you can, see Override the enter key, but keep default behavior for other keys in a wpf datagrid

Short: Derive a custom NoEnterDataGrid class, and prevent the base class from handling OnKeyDown() when it is an enter press.

1.: Using the KeyDown event might help, since it might be executed before the cell selection movement. If you don't want to execute the action right away, store the current cell in KeyDown, and execute your action in KeyUp -- but beware that this might cause strange behaviour if the user clicks in the datagrid while holding Enter pressed.