如何在 MVVM Light 框架中使用 RelayCommand [英] How to use RelayCommand with the MVVM Light framework
问题描述
我刚刚开始学习 MVVM Light 框架,我找不到任何关于如何使用 RelayCommand 的简单示例.出于学习目的,我只想在我的视图中有一个按钮,单击该按钮时会显示一个 hello world world 消息框,并且每偶数分钟启用一次(基本上如果 DateTime.Now.Minute % 2 == 0).
I've just started learning the MVVM Light framework and I can't find any straightforward examples on how to use a RelayCommand. For purposes of learning, I'd just like to have a button in my view which when clicked show's a hello world world message box, and which is enabled on every even minute (basically if DateTime.Now.Minute % 2 == 0).
按钮 XAML 的外观以及 RelayCommand HelloWorld 将如何在 ViewModel 中定义?
How would the button XAML look and how would the RelayCommand HelloWorld be defined in the ViewModel?
感谢您的帮助!!
推荐答案
RelayCommand
的目的是实现Button控件需要的ICommand
接口,并且只传递调用其他一些函数,这些函数通常在 ViewModel 中紧挨着它们.
RelayCommand
's purpose is to implement the ICommand
interface that Button controls needs and to just pass the calls onto some other function which generally sits right next to them in the ViewModel.
例如,您将有一个 ViewModel 类,如:
So for example, you would have a ViewModel class like:
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={StaticResource ...}
In your control you would have the DataContext
set either in the code behind or in the XAML directly through a DataContext={StaticResource ...}
然后您的按钮将像这样绑定到 ViewModel 中的命令
Your button would then bind to the command in the ViewModel like so
<Button Content='Push me' Command='{Binding DisplayMessageCommand}' />
当按钮被点击时,它使用 DisplayMessageCommand
并在这个对象上调用 Execute()
,RelayCommand
只是转发到 DisplayMessage
方法.
When the Button is clicked, it uses the DisplayMessageCommand
and calls Execute()
on this object which RelayCommand
just forwards onto the DisplayMessage
method.
DispatchTimer
每分钟关闭一次并调用 RaiseCanExecuteChanged()
.这允许绑定到命令的按钮重新检查命令是否仍然有效.否则,您可能会单击该按钮,却发现该命令当前不可用.
The DispatchTimer
goes off once a minute and calls RaiseCanExecuteChanged()
. This allows the button which is bound to the command to re-check if the command is still valid or not. Otherwise, you might click the button only to find out that the command isn't currently available.
这篇关于如何在 MVVM Light 框架中使用 RelayCommand的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!