5
votes

The handler of the "SelectionChanged" event of the ComboBox control has the following signature:

void SelectionChangedMethod(object sender, SelectionChangedEventArgs e)

How to bind to that property under Silverlight 4 and MVVM-Light to the corresponding method of the ViewModel object?

As far as I know, I need to do something like this:

public void Changed(Object obj, SelectionChangedEventArgs e)
{
    // .... implement logic here
}

RelayCommand<Object, SelectionChangedEventArgs> _command;
public ICommand ObjectSelectionChanged
{
    get
    {
        if (_command == null)
        {
            _command = new RelayCommand<Object, SelectionChangedEventArgs>(Changed);
        }
        return _command;
    }
}

The problem is that RelayCommand class in the MVVM-Light framework doesn't support 2 generic parameters...

Is there any solution or workaround for this case? How bind control event to the method with 2 parameters?

And another problem: ComboBox doesn't have "Command" property to bind this command..? How can I get event to the ViewModel?

Thanks.

P.S. I've tried to use SelectedItem property of the combobox, but it seems like ComboBox implementation is not correct and it doesn't work...

1

1 Answers

25
votes

There is a much easier approach then trying to connect the SelectedChangedEvent.

Try...

<ComboBox ItemsSource={Binding Path=Names} SelectedItem={Binding Path=SelectedName, Mode=TwoWay}>

public class ViewModel : ViewModelBase
{
    private string _selectedName;
    public string SelectedName
    {
        get { return _selectedName; }
        set
        {
            if (_selectedName == value) return;
            _selectedName = value;
            RaisePropertyChanged("SelectedName");
        }
    }
}

It is possible to do it the way you were going

<GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding MyCommand}" PassEventArgsToCommand="True"/>

The Command should be a RelayCommand of type 'SelectionChangedEventArgs'