Mvvm-Light Silverlight, using EventToCommand with a Combobox

▼魔方 西西 提交于 2019-11-30 01:21:23
bplus

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];
}

You may try adding a CommandParameter and passing a list to your relayCommand

Something similar is described towards the bottom of this page but with a datagrid: http://mvvmlight.codeplex.com/ The code from that page looks like this:

<sdk:DataGrid x:Name="MyDataGrid" ItemsSource="{Binding Items}">
   <i:Interaction.Triggers> 
   <i:EventTrigger EventName="SelectionChanged">  
   <cmd:EventToCommand  Command="{Binding SelectionChangedCommand}"
                        CommandParameter="{Binding SelectedItems, ElementName=MyDataGrid}" />
   </i:EventTrigger>
   </i:Interaction.Triggers>
</sdk:DataGrid>

If you do this, your relayCommand would need to deal with the parameters coming in. Something like this in your ViewModel:

public RelayCommand<IList> SelectionChangedCommand{    get;    private set;}

...

SelectionChangedCommand = new RelayCommand<IList>(
    items =>
    {
        if (items == null)
        {
            NumberOfItemsSelected = 0;
            return;
        }
        //Do something here with the records selected that were passed as parameters in the list
        //example:  NumberOfItemsSelected = items.Count;
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!