MVVM Focus To Textbox

I have documented a "pure MVVM" way to do this in my answer to a similar problem. The solution involves using Attached Properties and a framework for passing interface commands from the ViewModel back to the View.


The simple way is to set focus in UserControl_Load event

        this.txtBox.Focus();
        txtBox.Focusable = true;
        Keyboard.Focus(txtBox);

MVVM doesn't mean you can not put code in the code behind file. In fact, Do not let any pattern restrict you to find the best way of coding.


As I believe in MVVM having a Name element usually means bad design?

No, it’s not.

The MVVM pattern is not about eliminating all the code from code-behind files.

It is about separating of concerns and increasing the testability. View related code like focus handling should remain in the code-behind file of the View. But it would be bad to see application logic or database connection management in the code-behind file of the View.

MVVM examples with code in the code-behind files without violating the MVVM pattern can be found at the WPF Application Framework (WAF) project.

Tags:

Wpf

Textbox

Mvvm