如何在MVVM中使用命令 [英] How to use Commands in MVVM
本文介绍了如何在MVVM中使用命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的模特:
my model :
class Login
{
public string Name{ get; set; }
public string Password { get; set; }
}
我的视图模型:
my view model :
class LoginViewModel : ObservableObject, INotifyPropertyChanged, ICommand
{
class LoginViewModel
{
Models.Login _mylogin = new Models.Login();
}
}
private readonly Models.Login _mylogin;
public string Name
{
get { return _mylogin.Name; }
set { _mylogin.Name= value; NotifyPropertyChanged("Name"); }
}
public string Password
{
get { return _mylogin.Password; }
set { _mylogin.Password = value; NotifyPropertyChanged("Password"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
问题:实施最简单的方法是什么icommand? 。这是我第一个使用MVVM patern的wpf示例。我想知道命令是如何工作的。(对不起我的英语不好)
Question: What is the easiest way to implement icommand ? . this is my first wpf example with MVVM patern . i would like to know how command works.(sorry for my poor english)
推荐答案
对MVVM的一些好的支持可以在Josh Smith的MVVM Foundation库 [ ^ ]。
有一个RelayCommand
的实现和其他非常有用的东西!
Some good support for MVVM can be found in Josh Smith's MVVM Foundation library[^].
There is an implementation ofRelayCommand
and other quite useful stuff!
你绝对是应该做更多的阅读。但是为了让你开始......
你不希望你的VM实现ICommand。命令是VM公开的单独对象。为避免为每个命令创建一个类,使用名为DelegateCommand或RelayCommand的通用实现。您可以自己实现一个或使用一个MVVM框架(例如Prism,此处提供更多链接)。作为name表明该命令会将调用转发给您在构造函数中提供的委托。以下是它的工作原理:
You definitely should do more reading. But to get you started...
You don't want your VM to implement ICommand. Commands are separate objects exposed by your VM. To avoid creating a class for each command a common implementation named DelegateCommand or RelayCommand is used. You can implement one yourself or use one which comes with a MVVM framework (e.g. Prism, some more links here). As the name suggest the command will relay the call to a delegate you provide in the constructor. Here is how it works:
class LoginViewModel
{
ICommand MyCommand { get; private set; }
public LoginViewModel()
{
MyCommand = new DelegateCommand(MyMethod);
}
private void MyMethod(object parameter)
{
// handle the call here
}
}
这篇关于如何在MVVM中使用命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文