2

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:

  • Is this the correct way?
  • Is there a way I can propogate the (object sender, RoutedEventArgs e) parameters into my viewmodel and should I care if its not there?
  • Suppose if this were a listbox selection changed event and not a button click. How do I get the value of the selected item without the object sender, SelectionChangedEventArgs e parameters?
4

2 回答 2

3

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.

于 2011-01-03T21:54:58.677 回答
2

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!

于 2011-01-03T19:02:00.193 回答