Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM Focus To Textbox

Tags:

mvvm

wpf

textbox

How would I set focus to a TextBox without specifying the name for that TextBox? At the moment I am doing the following

<Window FocusManager.FocusedElement="{Binding ElementName=Username}">
    <Grid>
        <TextBox Text="{Binding Username}" Name="Username" />            
    </Grid>
</Window>

Is there any way of doing this without specifying a Name for the TextBox. As I believe in MVVM having a Name element usually means bad design?

like image 645
Michal Ciechan Avatar asked May 14 '10 14:05

Michal Ciechan


1 Answers

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.

like image 151
jbe Avatar answered Sep 17 '22 17:09

jbe