[MVVM Native] use of native MVVM, mvvm
I. Preface
A task needs to be completed a few days ago, which belongs to some of the company's core code. To avoid unnecessary troubles, the task must not use a third-party MVVM framework, but must use a native one.
I usually get used to Dev and MVVMLight. I can't tell the truth from the native, so I wrote it as a memorandum. (The old driver can skip this page)
Ii. Sample Code
The View part is skipped. Check the Model part:
Public class Model: INotifyPropertyChanged {
Public string Isbn {get; set;} public string Description {get; set ;}
// Attribute values to be changed: private string _ AS; public string AS {get {return _ AS;} set {_ AS = value; policypropertychanged ("");}} public event PropertyChangedEventHandler PropertyChanged; private void policypropertychanged (string name) {PropertyChanged ?. Invoke (this, new PropertyChangedEventArgs (name ));}}
ViewModel section:
public class VM : INotifyPropertyChanged{ private string currentIsbn = string.Empty; public string CurrentIsbn { get { return currentIsbn; } set { currentIsbn = value; NotifyPropertyChanged("CurrentIsbn"); } } public ObservableCollection<Model> Isbns { get; set; } private ICommand _confirmCmd; public ICommand ConfirmCmd { get { return _confirmCmd ?? (_confirmCmd = new ConfirmFunction(this)); } set { _confirmCmd = value; } } public VM() { Isbns = new ObservableCollection<Model>(); } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } } public class ConfirmFunction : ICommand { private VM vm; public ConfirmFunction(VM _vm) { this.vm = _vm; } public bool CanExecute(object parameter) { return true; } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { // do your job } }
Summary:
1. Model and ViewModel inherit INotifyPropertyChanged
2. Bind fields that interact with the View in the following format:
Private string _;
Public string
{
Get
{
Return _;
}
Set
{
_ A = value;
NotifyPropertyChanged ("");
}
}
3. All commands are of the ICommand type, and then completed through Delegate in the preceding format.
4. When writing the Command class, VS will prompt you what methods are needed. Hahaha