MVVM community toolkit KeyUp event

86 Views Asked by At

Can someone please explain me how to get KeyUp event in view model?

I have tried with this:

in my view:

<TextBox .....>
<i:Interaction.Triggers>
    <i:EventTrigger EventName="KeyUp">
      <ei:CallMethodAction TargetObject="{Binding}" MethodName="Search"/>
    </i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>

In my view model:

[RelayCommand]
private void Search()
{
    // ....
}

Thank you.

I and getting errors with message that method with correct signature cannot be found on my view model.

I have tried also with

[RelayCommand]
private void Search(KeyEventArgs)

[RelayCommand]
private void Search(EventArgs)

[RelayCommand]
private void Search(object)
1

There are 1 best solutions below

0
Tarazed On

You are creating a command object through CommunityToolkit's generators. So instead of a method call you want to invoke that command. The generators append the word "Command" to the method name when creating a RelayCommand.

<TextBox Name="searchTextBox" .....>
<i:Interaction.Triggers>
    <i:EventTrigger EventName="KeyUp" SourceObject="{Binding ElementName=searchTextBox}">
      <ei:InvokeCommandAction Command="{Binding SearchCommand}" />
    </i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>

You can also add a CommandParameter as needed if you need to provide something (such as a search string?). Further examples are here.