EventToCommand fails for the initial GotFocus event

675 Views Asked by At

I begin to apply the Mvvm design pattern in my current project and the framework I used is Mvvm Light toolkit. Now I encoutered a problem when using the EventToCommand to handle "GotFocus" event. The xaml file is something like:

<TextBox x:Name="TextBox1">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="GotFocus">
            <cmd:EventToCommand Command="{Binding TestCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
 </TextBox>

I want to execute the TestCommand in the view model whenever the "GotFocus" is fired. But the problem is that the "TestCommand" is not executed for the initial "GotFocus"(ie. when the window is loaded). I have debugged and found that the "GotFocus" event was actually fired but the Trigger was not invoked for unknown reason. Then I set the focus in the "Window.Loaded" event handler, it still failed.

protected void WindowLoaded(object sender, RoutedEventArgs e)
    {
        FocusManager.SetFocusedElement(this, TextBox1); // The focus is moved to TextBox1 but the associated command is not executed.
    }

But If I set the focus in the "Window.Activated" event handler, it is OK.

    protected void WindowActivated(object sender, EventArgs e)
    {
        FocusManager.SetFocusedElement(this, TextBox1); // The focus is moved to TextBox1 and the command is executed.
    }

I am very confused about what happened. Could anyone explain it in detail?

0

There are 0 best solutions below