0

I've tried -this- but it seems not work in WPF,

and saw -here- it says it'll be complicated.

So how to detect the current focused textbox in C# WPF?

Community
  • 1
  • 1
yu yang Jian
  • 6,680
  • 7
  • 55
  • 80
  • 1
    Could you not just loop through the controls and check which is "focused"? – Hexie May 03 '16 at 04:08
  • 1
    Alternatively, could you not just do this: http://stackoverflow.com/questions/5317150/how-to-get-the-focused-control-in-wpf what you looking for? – Hexie May 03 '16 at 04:14
  • 3
    I can't really think of any reason you would ever do this in WPF. In the overwhelming majority of cases you're not interested in the control itself, you're interested in the data that the currently focused control represents. If you're using data binding (which you should be) then you should bind the focus event to a handler in your DataContext. Alternatively, if you insist on doing it the wrong way then see the answer to [this question](http://stackoverflow.com/questions/19392036/get-currently-focused-element-control-in-a-wpf-window). – Mark Feldman May 03 '16 at 04:18

1 Answers1

2

There seem to be a few ways of doing this, depending on what it is exactly that you are wanting.

  • Loop through all the controls (of type TextBox) and check the focused property (ensure controls are set to focusable).
  • Use the FocusManager.GetFocusedElement method
  • Consider using this SO answer, snippet - UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
Community
  • 1
  • 1
Hexie
  • 3,955
  • 6
  • 32
  • 55