如何在MVVM Light框架中使用RelayCommand

时间:2011-07-19 21:56:41

标签: c# wpf mvvm mvvm-light

我刚开始学习MVVM Light框架,但我找不到任何关于如何使用RelayCommand的简单示例。出于学习的目的,我只想在我的视图中有一个按钮,当点击时显示一个hello world world消息框,并且每隔一分钟启用一次(基本上如果DateTime.Now.Minute%2 == 0)

按钮XAML如何显示以及如何在ViewModel中定义RelayCommand HelloWorld?

感谢您的帮助!!

2 个答案:

答案 0 :(得分:42)

RelayCommand的目的是实现Button控件所需的ICommand接口,并将调用传递给ViewModel中通常位于它们旁边的其他函数。

例如,您将拥有一个ViewModel类,如:

class HelloWorldViewModel : ViewModelBase
{
    public RelayCommand DisplayMessageCommand { get; private set; }

    private DispatchTimer _timer;

    public HelloWorldViewModel()
    {
        this.DisplayMessageCommand = new RelayCommand(this.DisplayMessage, CanDisplayMessage);

        // Create a timer to go off once a minute to call RaiseCanExecuteChanged
        _timer = new DispatchTimer();
        _timer = dispatcherTimer.Tick += OnTimerTick;
        _timer.Interval = new Timespan(0, 1, 0);
        _timer.Start();
    }

    private void OnTimerTick(object sender, EventArgs e)
    {
        this.DisplayMessageCommand.RaiseCanExecuteChanged();
    }

    public bool CanDisplayMessage()
    {
        return DateTime.Now.Minute % 2 == 0;
    }

    public void DisplayMessage()
    {
        //TODO: Do code here to display your message to the user
    }
}

在您的控件中,您可以直接通过DataContext

在后面的代码中或在XAML中设置DataContext={StaticResource ...}

然后您的按钮将绑定到ViewModel中的命令,如此

<Button Content='Push me' Command='{Binding DisplayMessageCommand}' />

点击按钮时,它会使用DisplayMessageCommand并在此Execute()上转移RelayCommand的{​​{1}}方法上调用DisplayMessage

DispatchTimer每分钟发出一次,然后拨打RaiseCanExecuteChanged()。这允许绑定到命令的按钮重新检查命令是否仍然有效。否则,您可以仅单击该按钮以查明该命令当前不可用。

答案 1 :(得分:5)

或使用lambda

    private RelayCommand<anyobject> _AddCmd;
    public ICommand AddPoint
    {
        get
        {
            return _AddCmd ??
                (
                _AddCmd = new RelayCommand
                    (
                        (obj) =>
                        {
                            ViewModelWF.ZeroPoints.Add(new WM.Point(0, 0));
                        }
                    )
                );
        }
    }

    private RelayCommand _DeleteCmd;
    public ICommand DeletePoint
    {
        get
        {
            return _DeleteCmd ??
                (
                _DeleteCmd = new RelayCommand
                    (
                        () =>
                        {
                            int idx = wpfZeroPoints.SelectedIndex;
                        },
                        () =>
                        {
                            return wpfZeroPoints.SelectedIndex <= 0;
                        }
                    )
                );
        }
    }