简体   繁体   中英

Get currently selected cell on Enter pressed in a datagrid C# WPF

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM