2

I need to do some logic but only from a specific textbox. Trying to do some search it appears that there is no event for KeyDown or PreviewKeyUp for a textbox but for the entire window. So in XAML I have this

PreviewKeyUp="keyPressLogic" 

Then have a method that looks like this;

 private void keyPressLogic(object sender, KeyEventArgs e) { if ((e.Key == Key.Down) && (check focus command ) ) { //My logic return; } } 

As you can see I cannot figure out the check focus command. So either I am missing the key check on the textbox or got to find the focus command

thanks

1
  • 1
    Try (sender as TextBox).IsFocused Commented Oct 17, 2013 at 19:31

2 Answers 2

3

To get the textbox you pressed you should:

TextBox textbox = (TextBox)sender; 

and then you can:

 private void keyPressLogic(object sender, KeyEventArgs e) { if ((e.Key == Key.Down) && (textbox.IsFocused)) { //My logic return; } } 
Sign up to request clarification or add additional context in comments.

4 Comments

Won't this just check to see if any textbox is in focus? The OP wanted a Specific textbox.
@Harrison, it will check any textbox that uses this function as the event handler. By the looks of things, that is only one textbox.
@gunr2171: So I have 2 textboxes and a checkbox. If textbox A is in focus when I call this, the if statement is true. If textbox B is in focus when I call this, the if statement is true. If the Checkbox is in focus I will have an invalid cast run-time error. Am I wrong?
@Harrison, true, but I think the only way this function is called is on a keypress event, which will give the focus to the control before the function is called. (actually, now that I think about it, this looks like a keyboard press, not a mouse press, so what's up with that?)
1

System.Windows.Controls.TextBox has an event caleed. Here you can find it. It will trigger the KeyDown event only for the textbox you add it on.

Here is how you add it into your XAML

<TextBox x:Name="MyTextbox" KeyDown="MyTextbox_KeyDown" /> 

And here is how your event handler should look like

private void MyTextbox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if(e.Key == Key.Down) { // Add your logic here } } 

Comments