Eva*_*van 21 c# wpf mvvm mvvm-light
我刚刚开始学习MVVM Light框架,但我找不到任何关于如何使用RelayCommand的简单示例.出于学习的目的,我只想在我的视图中有一个按钮,当点击时显示一个hello world world消息框,并且每隔一分钟启用一次(基本上如果DateTime.Now.Minute%2 == 0) .
按钮XAML如何显示以及如何在ViewModel中定义RelayCommand HelloWorld?
谢谢你的帮助!!
Mer*_*OWA 44
RelayCommand其目的是实现ICommandButton控件所需的接口,并将调用传递给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
}
}
Run Code Online (Sandbox Code Playgroud)
在您的控件中,您DataContext可以在后面的代码中或在XAML中直接通过a设置DataContext={StaticResource ...}
然后,您的按钮将绑定到ViewModel中的命令,就像这样
<Button Content='Push me' Command='{Binding DisplayMessageCommand}' />
Run Code Online (Sandbox Code Playgroud)
单击Button时,它使用DisplayMessageCommand和调用Execute()此对象,该对象RelayCommand只转发到DisplayMessage方法上.
在DispatchTimer一次熄灭一分钟,电话RaiseCanExecuteChanged().这允许绑定到命令的按钮重新检查命令是否仍然有效.否则,您可以仅单击该按钮以查明该命令当前不可用.
小智 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;
}
)
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
49980 次 |
| 最近记录: |