今天學了MVVM模式,這里貼一下具體步驟。
MVVM其實就是:Model 、view、viewmodel三個的簡稱,就像MVC一樣。
model就是模型。view就是視圖。viewmodel就是和view進行綁定的。
首先建立一個MainWindow。
然后建立相應的文件夾:一個ViewModels,一個views,一個Models。在viewmodels里面有一個基礎的通知類:NotifycationObject,這個類繼承自INotifyPropertyChanged,然后實現它就可以了。這個類是通知的基礎類,當事件執行時,會將相應的值顯示在綁定的控件上。
/// <summary> /// 通知基類。如果RaisePropertyChanged被調用,databinding就會調用PropertyChanged事件,將propertyName的值顯示在界面 /// </summary> class NotifycationObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChanged(string propertyName) { if (PropertyChanged!=null) { PropertyChanged.Invoke(this,new PropertyChangedEventArgs(propertyName)); } } }
然后我們需要建立一個Commands文件夾,里面有一個基礎的委托命令類:DelegateCommand。
class DelegateCommand : ICommand { public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) { if (CanExecuteFunc == null) { return true; } return this.CanExecuteFunc(parameter); } public void Execute(object parameter) { if (ExecuteAction == null) { return; } this.ExecuteAction(parameter); } public Action<object> ExecuteAction { get; set; } public Func<object, bool> CanExecuteFunc { get; set; } }
然后我們需要在ViewModel里面建一個與Window相應的ViewModel類。此類時需要綁定界面的控件的。viewmodel需要繼承
NotifycationObject
class MainWindowViewModel : NotifycationObject { private double input1; public double Input1 { get { return input1; } set { input1 = value; this.RaisePropertyChanged("Input1"); } } private double input2; public double Input2 { get { return input2; } set { input2 = value; this.RaisePropertyChanged("Input2"); } } private double result; public double Result { get { return result; } set { result = value; this.RaisePropertyChanged("Result"); } } public DelegateCommand AddCommand { get; set; } /// <summary> /// 當result被賦值之后,會調用屬性的set器。然后會調用RaisePropertyChanged的事件,而調用此事件之后,會將result顯示在界面上 /// </summary> /// <param name="obj"></param> private void Add(object obj) { this.Result = input1 + input2; } public MainWindowViewModel() { this.AddCommand = new DelegateCommand(); this.AddCommand.ExecuteAction = new Action<object>(Add); } }
其中:Input1、Input2、Result等3屬性是需要綁定在界面的三個textbox上的。而AddCommand是需要綁定在按鈕上的。AddCommand是需要傳遞給基礎委托命令類DelegateCommand的ExecuteAction的委托的,以此來綁定方法。
接下來就是綁定屬性到控件上了。
如圖所示。
最后就是將當前window的datacontext綁定viewmodel了,不然會找不到綁定的命令或者屬性。
好了,一個簡單的MVVM就完成了。
看看運行的結果
這是初始運行界面:只有默認值
點擊OK后:
。注意:我們這里是沒有給按鈕添加事件的,只給它了綁定的命令。這樣的好處就是當界面變化,我們可以改動最少的代碼。比如如果客戶讓你將textbox改成silder,你也不用再去添加事件啥的了,只需要改下綁定的屬性即可