0

I am trying to set focus on a text box. I tried set focus for cursor

but all that does is put the cursor there and freezes it. You can't actually type anything still. You end up still having to click the text box to type. I did exactly as they did in that question. I read some stuff about logical focus and physical focus? Not quite sure how to go about doing what I need. Do I need to create an attached property and handle it that way? I am trying to avoid code behind at all costs.

Also, after clicking a "Submit" button I would like to have it set focus back to the text box again

Here is the code I tried, the FocusManager is on a grid that wraps the textbox:

FocusManager.FocusedElement="{Binding ElementName=FocusedTextBox}"


<TextBox Text="{Binding serialNumber}"
         x:Name="FocusedTextBox">
</TextBox>

As I said, all this did is put the cursor there and you can't type anything until you again click in the text box. Any suggestions?

Thanks,

Eric Obermuller
  • 245
  • 3
  • 19
  • 1
    why are you trying to avoid the code behind at all costs? sounds to me like you'll want to make use of event handlers, which will reside in your code behind... – trix Jul 31 '18 at 21:01
  • Because using code behind is just bad practice in general. I'd rather use attached properties and maintain MVVM – Eric Obermuller Jul 31 '18 at 22:29

1 Answers1

0

Just give the textbox a name (e.g. "theTextBox') and call theTextBox.Focus().

If you're trying to do this in MVVM with data-binding (and you should be) then you can use an attached property to bind to a property in your view model.

Mark Feldman
  • 15,731
  • 3
  • 31
  • 58