Silverlight+MVVM-Light中的SelectionChanged事件绑定

5

"SelectionChanged"事件的ComboBox控件处理程序具有以下签名:

void SelectionChangedMethod(object sender, SelectionChangedEventArgs e)

如何在Silverlight 4和MVVM-Light下将属性绑定到ViewModel对象的相应方法?

据我所知,我需要像这样做:

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

问题在于MVVM-Light框架中的RelayCommand类不支持2个泛型参数...
对于这种情况,是否有解决方案或解决方法?如何将控件事件绑定到具有2个参数的方法?
还有另一个问题:ComboBox没有“Command”属性来绑定此命令...如何将事件传递到ViewModel?
谢谢。
附注:我尝试使用combobox的SelectedItem属性,但似乎ComboBox的实现不正确,它无法正常工作...
1个回答

25

与其尝试连接 SelectedChangedEvent,不如采用更简单的方法。

尝试...

<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");
        }
    }
}

你可以按照你之前的方式来完成它。

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

该命令应该是一个类型为'SelectionChangedEventArgs'的RelayCommand。


谢谢,Mode=TwoWay - 这对我来说是必要的,让它可行...但第二种方法是什么?我如何使用这个“EventToCommand”?谢谢。 - Budda
哇,第一种方法太棒了!非常感谢! - Yoo Matsuo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接