Search code examples
c#wpfeventskeyenter

How to detect forward slash and if condition is satisfied check for Enter Key C# WPF


I'm working on wpf application which is contained of main Window.xaml with DataGrid on it and articles inside ofcourse, and I should do next, if user select article and press " / ", than I should let him edit price - unlock field with price, and when user is done he should hit enter, and after that I should check is enter hitted so I can update new price for that article.

First of all, this is how I'm checking is "/" pressed because I couldn't fight right OEM for this key, and I'm afraid of what could happen when user changes language on his keyboard, so I did it on this way.

 private void Window_PreviewTextInput_1(object sender, TextCompositionEventArgs e)
        {
            if (e.Text == "/")
            {

                    if (globalTemp != null)
                    {
                        txtPrice.IsEnabled = true;

                    }
             }

        }

After I give oportunity to user to change price, I should update article price on Enter key, so how could I check after this condition if (e.Text == "/") is enter also clicked, because as I saw there is no e.Key in this TextCompositionEventArgs e...

E D I T :

Maybe I could simply attach new event here, so in fact I might have two events, first one to detect "/" and to unlock txtPrice, and another one to update it if enter is pressed, so another event might look like this:

 private void txtPrice_KeyDown(object sender, KeyEventArgs e)
 {
   if (e.Key == Key.Return)
   {
     // UPDATE PRICE HERE 
   }   
} 

Thanks guys Cheers


Solution

  • Handle the PreviewKeyDown event to detect ENTER key presses and the PreviewTextInput event to detect "/".

    After all ENTER is not a character and "/" is not a key so it makes perfect sense to handle both these events separately.

    If you want to detect the combined ENTER + "/" key combination you could use a Boolean field that keeps track of whether "/" was pressed right before ENTER was pressed:

    private bool _slash = false;
    private void Window_PreviewTextInput_1(object sender, TextCompositionEventArgs e)
    {
        if (e.Text == "/")
        {
            _slash = true;
            e.Handled = true;
            //...
        }
        else
        {
            _slash = false;
        }
    }
    
    private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == System.Windows.Input.Key.Enter && _slash)
        {
            // "/" + ENTER was pressed...
        }
    }