Search This Blog

Monday, September 12, 2011

Silverlight; TextBox.TextChanged event in ViewModel; Firing command with command parameter in MVVM using MVVM Light Toolkit from Galasoft.ch

 

This code does two things: updates designated property in View class and fires a command in ViewModel based on some event from TextBox. In our case the event is TextChanged.
This is a real MVVM solution to this problem. You can download MVVM Light toolkit from http://www.galasoft.ch/mvvm/installing/#binaries.


<TextBox Name="textBox1" Text="{Binding Name, Mode=TwoWay}">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="TextChanged">
                            <!-- Update property in View class -->
                            <ei:ChangePropertyAction PropertyName="MarkEditionStatus" Value="True" TargetName="SomePropertyInViewClass" />
                            <!-- Fire a command in ViewModel
                            <cmd:EventToCommand Command="{Binding TextBox_TextChanged, Mode=OneWay}"
                                CommandParameter="{Binding Text, ElementName=textBox1, Mode=OneWay}"
                                MustToggleIsEnabledValue="True" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </TextBox>

#region TextBoxFunctions

ViewModel:

public ViewModelConstructor(....)
{
    [....]
   
    [....]
    TextBox_TextChanged = new ActionCommand((o) => textBox_TextChanged(o));
}

#region TextBoxFunctions

public ICommand TextBox_TextChanged { get; private set; }

private void textBox_TextChanged(object arg)
{
    MessageBox.Show("AAA");
}

#endregion TextBoxFunctions

1 comment:

  1. You can also do it like this:

    <i:Interaction.Triggers>
    <i:EventTrigger
    EventName="TextChanged">
    <i:InvokeCommandAction
    Command="{Binding DataContext.DefaultCommand, ElementName=browser}"
    CommandParameter="{Binding AAA, Source=myGrid" />
    </i:EventTrigger>
    </i:Interaction.Triggers>

    as cmd:EventToCommand is from MVVM toolkit.

    ReplyDelete

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