How to give an element focus when something happens?

I had a very simple problem: On loading of particular screen I wanted to give a TextBox focus. It’s freaking easy to do this in the code behind. Most of my applications are actually MVVM applications and in that case it’s not something for the ViewModel, it’s logic that belongs to the view. But how about a Behavior?

I want to give a specific control focus when something happens on something else. So that should be a TargetedTriggerAction<T>, T should be Control, because that’s something you can give focus. How easy can it be?

public class FocusOnEvent : TargetedTriggerAction<Control>
{
    protected override void Invoke(object parameter)
    {
        Target.Focus();
    }
}

Is that all? Yes it is, or actually, I want to make it even easier, add the default trigger using the DefaultTriggerAttribute. Default should be the Loaded event, so let’s add that single line.

[DefaultTrigger(typeof(FrameworkElement), typeof(EventTrigger), "Loaded")]
public class FocusOnEvent : TargetedTriggerAction<Control>
{
    protected override void Invoke(object parameter)
    {
        Target.Focus();
    }
}

Now we have this easy code, how do we use it? Just add a little bit of xaml to your page / control, just like any other behavior.

<i:Interaction.Triggers>
    <i:EventTrigger>
        <Behaviors:FocusOnEvent TargetName="TitleTextBox" />
    </i:EventTrigger>
</i:Interaction.Triggers>

Some second thoughts, is it required to take the Safe event Detachment base class for Windows Phone Behaviors by Joost van Schaik into consideration? No it’s not required, because we’re not manually attaching handlers to the events, that’s all done by the TargetedTriggerAction itself. Hope you guys think this little bit of code is useful.

Gravatar