現在のプロジェクトでMvvmデザインパターンの適用を開始し、使用したフレームワークはMvvmLightツールキットです。EventToCommandを使用して「GotFocus」イベントを処理するときに問題が発生しました。xamlファイルは次のようなものです。
<TextBox x:Name="TextBox1">
<i:Interaction.Triggers>
<i:EventTrigger EventName="GotFocus">
<cmd:EventToCommand Command="{Binding TestCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
「GotFocus」が起動されるたびに、ビューモデルでTestCommandを実行したいと思います。ただし、問題は、最初の「GotFocus」に対して「TestCommand」が実行されないことです(つまり、ウィンドウがロードされたとき)。デバッグしたところ、「GotFocus」イベントが実際に発生したのに、不明な理由でトリガーが呼び出されなかったことがわかりました。次に、「Window.Loaded」イベントハンドラーにフォーカスを設定しましたが、それでも失敗しました。
protected void WindowLoaded(object sender, RoutedEventArgs e)
{
FocusManager.SetFocusedElement(this, TextBox1); // The focus is moved to TextBox1 but the associated command is not executed.
}
しかし、「Window.Activated」イベントハンドラーでフォーカスを設定すれば、問題ありません。
protected void WindowActivated(object sender, EventArgs e)
{
FocusManager.SetFocusedElement(this, TextBox1); // The focus is moved to TextBox1 and the command is executed.
}
私は何が起こったのか非常に混乱しています。誰かがそれを詳細に説明できますか?