views:

326

answers:

2

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?

+2  A: 

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.

Joseph Sturtevant
http://geekswithblogs.net/HouseOfBilz/archive/2009/08/27/adventures-in-mvvm-ndash-binding-commands-to-any-event.aspx
Agies
+2  A: 

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.

jbe