Mvvm-Light Silverlight, using EventToCommand with a Combobox

bplus picture bplus · Jun 28, 2010 · Viewed 12.3k times · Source

I've hooked up a ComboBox's SelectedItemChangeEvent to a ICommand in my view model. Everything seems to be working fine however I do not know how to get the SelectedItem of the ComboxBox. I think I need to use the CommandParameter of the EventToCommand - do I bind this to something in my ViewModel that has the selectedItem of the ComboBox? I've tried this:

<ComboBox 
  Width="422"
  Height="24"
  DisplayMemberPath="Name"
  ItemsSource="{Binding CategoryTypes}"
  SelectedItem="{Binding SelectedCategory}"
  >
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <MvvmLight:EventToCommand 
              Command="{Binding SelectCategoryCommand,Mode=TwoWay}"
              CommandParameter="{Binding SelectedCategory, Mode=TwoWay}"
              MustToggleIsEnabledValue="True" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ComboBox>

and in my view model:

public ICommand SelectCategoryCommand
{
    get
    {
        return new SelectCategoryCommand(this);
    }
}

public CategoryType SelectedCategory
{
    get; set;
}

and the ICommand

public class SelectCategoryCommand : ICommand
{
    private RowViewModel _rowViewModel;

    public SelectCategoryCommand(RowViewModel rowViewModel)
    {
        _rowViewModel = rowViewModel;
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        CategoryType categoryType = (CategoryType) parameter;
    }

}

However the Parameter in the Execute method of the ICommand is always null. I'm stil quite inexperienced with SilverLight so I think I'm really missing something obvious here. Can anyone help? Thanks in advance!

Answer

bplus picture bplus · Jun 28, 2010

After doing some digging I found that it is very simple to pass the actual SelectionChangedEventArgs as ICommand's execute parameter:

Just set PassEventArgsToCommand="True"

<ComboBox Width="422"
          Height="24"
          DisplayMemberPath="Name"
          ItemsSource="{Binding CategoryTypes}"
          SelectedItem="{Binding SelectedCategory}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <MvvmLight:EventToCommand Command="{Binding SelectCategoryCommand,Mode=TwoWay}"
                                      MustToggleIsEnabledValue="True" 
                                      PassEventArgsToCommand="True"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ComboBox>

And then in the Execute method do something like:

public void Execute(object parameter)
{
    SelectionChangedEventArgs e = (SelectionChangedEventArgs)parameter;
    CategoryType categoryType = (CategoryType)e.AddedItems[0];
}