Search code examples
c#wpfprism

C# WPF Prism - Trigger Method is not called


The method MyMethod in my ViewModel is always called when the textbox gets the focus or loses the focus. But if I now delete the focus with Keyboard.ClearFocus(), then the method MyMethod is not called. Is there a better way to solve this or am I doing something wrong?

View:

<TextBox x:Name="MyTextBox" HorizontalAlignment="Left" Margin="35,237,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Text="{Binding MyTextBoxText}">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="LostFocus">
                    <prism:InvokeCommandAction Command="{Binding MyCommand}">
                        <prism:InvokeCommandAction.CommandParameter>
                            <MultiBinding Converter="{StaticResource multiParameterConverter}">
                                <Binding Path="Name" ElementName="MyTextBox"/>
                                <Binding Path="IsFocused" ElementName="MyTextBox"/>
                            </MultiBinding>
                        </prism:InvokeCommandAction.CommandParameter>
                    </prism:InvokeCommandAction>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </TextBox>

ViewModel:

public DelegateCommand<object> MyCommand=>
      _myCommand ??= new DelegateCommand<object>(MyMethod);  

private void MyMethod(object myObject)
{
  //Do something
}

Code Behind:

private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
   Keyboard.ClearFocus();
}

Solution

  • I think you mix up "focus" and "keyboard focus". Keyboard.ClearFocus() clears a Keyboard focus, not "focus". So to call a command also for "keyboard focus" yo can subscribe:

    <i:Interaction.Triggers>
       <i:EventTrigger EventName="LostKeyboardFocus">
          <i:InvokeCommandAction Command="{Binding MyCommand}"/>
       </i:EventTrigger>
    </i:Interaction.Triggers>  
    

    Watch out, if you leave also LostFocus, the command can be called several times.