Search This Blog

Friday, December 23, 2011

Silverlight passing event arguments in InvokeCommandAction; invoke a command when ENTER is pressed in a TextBox; Silverlight MVVM calling method from ViewModel with parameters

We need to trigger a command in ViewModel from View and pass arguments in response to an event. There are a couple of ways to accomplish that.

1. Just call a method from ViewModel:

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


2. Call a Command from ViewModel with parameters:
<TextBox Name="textBox">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="KeyDown">
            <i:InvokeCommandAction  
                    Command="{Binding SomeCommand}"  
                    CommandParameter="{Binding Text, ElementName=textBox}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <i:Interaction.Behaviors>
        <behaviors:UpdateTextBindingOnPropertyChanged />
    </i:Interaction.Behaviors>
</TextBox>

3. Call command in ViewModel and pass arguments in response to an event

<TextBox>
    <i:Interaction.Triggers>
        <Triggers:TextBoxEnterKeyTrigger>
            <Triggers:ExecuteCommandAction Command="SomeCommand" />
        </Triggers:TextBoxEnterKeyTrigger>
    </i:Interaction.Triggers>
</TextBox>

TextBoxEnterKeyTrigger source can be found here.

2 comments:

  1. What about sending EventArgs (for instance MouseEventArgs for MouseMove event) ?

    ReplyDelete

If you like this post, please leave a comment :)