I have a WPF ComboBox which has its IsEditable property bound to a view model which can switch it on and off. When it is switched on, I want to give focus to the ComboBox and select all the text in the edit TextBox.
I can’t see the best to accomplish this. Should I replace the ControlTemplate, subclass the ComboBox base class, and provide the needed properties, use Attached Properties, or some other approach?
I have a solution for you.
I’m using a combination of Model-View-ViewModel and Attached Property approach.
Firstly, you need to know the Messaging system in MVVM for this to work, as well as know your Commands. So starting with Attached Properties, we begin to set an IsFocused event to the combo box we would like to have focused and all text selected.
What this code shows is when we set the Attached Property SelectWhenFocused to true, it will register to listen for the GotFocused Event and select all the text inside.
To use is simple:
Now we need a button that will set the focus on the ComboBox when clicked on.
Notice how the CommandParameter is binding to the ComboBox by its name EditBox. This is so when the command executes, only this ComboBox gets focused and all text selected.
In my ViewModel, I have the Focus command declared as following:
This is a tested and proven technique that works for me. I hope it’s not an overkill solution to your problem. Good luck.