Search code examples
wpfmvvmtextbox

MVVM Focus To 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?


Solution

  • 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.