Silverlight Focus Action

Download action: FocusAction.zip

Download demo project: MVVMFocusTextbox

When I use MVVM in my projects I try to avoid writing code in the code behind (.xaml.cs). Although I DO think it’s valid to write User-Interface-specific code in the code behind, I’m always looking for a code-behind-less solution.

Problem

Setting a textbox focus in a MVVM solution is done from the code behind.

Solution

Use a FocusAction on a TextBox that is triggered from your ViewModel. Download FocusAction.zip and add it to your project. Drop the FocusAction on a User Element and set the folowing properties:

trigger

In xaml it looks like:

<i:Interaction.Triggers>
    <i:EventTrigger SourceObject=”{Binding Mode=OneWay}” EventName=”NewTask”>
        <Focus:FocusAction TargetObject=”{Binding ElementName=textBox, Mode=OneWay}” TargetName=”textBox”/>
    </i:EventTrigger>
</i:Interaction.Triggers>

Of course you may use any other event like an ItemChanged event to trigger the FocusAction.