user20358
user20358

Reputation: 14736

Silverlight MVVM: where did my (object sender, RoutedEventArgs e) go?

I am using commanding in my viewmodel to handle events. like for example I am handling a button click event like this:

XAML

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

                </i:EventTrigger>
            </i:Interaction.Triggers>

Viewmodel Code

   public ICommand mvvmButtonclick
    {
        get;
        private set;
    }

Viewmodel Constructor code to wireup the command

this.mvvmButtonclick = new ActionCommand(this.ButtonClickedEvent);

Actual method in the viewmodel that gets called on button click

   private void ButtonClickedEvent()
    {
        MessageBox.Show("worked!!!");
    }

This works. So my questions are:

Upvotes: 2

Views: 2100

Answers (2)

Geert van Horrik
Geert van Horrik

Reputation: 5724

There are some frameworks (such as Catel), that allow the forwarding of the EventArgs. For example, see this implementation:

http://catel.codeplex.com/SourceControl/changeset/view/508b404f2c57#src%2fCatel.Windows35%2fMVVM%2fCommands%2fCommand.cs

The class is compatible with both Silverlight and WPF.

If you don't want to use the EventArgs, you will need to create a SelectedObject property on the ViewModel and bind it to the SelectedItem of the listbox.

Catel includes 2 example applications (both in WPF and Silverlight) that use MVVM and the EventToCommand class to edit a selected item in a listbox. I think that is what you are looking for!

Upvotes: 2

AnthonyWJones
AnthonyWJones

Reputation: 189437

I think you may be missing the point of the separation between view and view-model that the interaction triggers are designed to provide.

The purpose of the interaction triggers is to allow the designer (typically using Blend) to invoke a command on the view model. Which UI element and which event on the UI element might invoke such a command is the designers choice.

If the ViewModel though did require that a specific derivative of the EventArgs be provided during such a call to a command then that would tie the designers hands a little. It would create the sort of coupling between the view and view-model that interaction triggers aspires to eliminate.

As to your final question, the way to determine the currently selected item in a list box and be notified when it changes would be to create a property on the view model that is the bound to the SelectedItem of the ListBox. There is no need to employee interaction triggers or commands for this sort of thing.

Upvotes: 3

Related Questions