Mvvm-Light Silverlight, using EventToCommand with a Combobox

后端 未结 2 2025
情歌与酒
情歌与酒 2020-12-24 15:03

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 o

相关标签:
2条回答
  • 2020-12-24 15:35

    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;
        });
    
    0 讨论(0)
  • 2020-12-24 15:49

    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];
    }
    
    0 讨论(0)
提交回复
热议问题