一、前言

      前些天需要完成一个任务,该任务属于公司的一些核心代码,为了避免不必要的麻烦,任务要求不能使用第三方的MVVM框架,必须用原生的。

       平时习惯了Dev与MVVMLight,遇上原生的说实话还真不会,于是写下来当做备忘录。  (界面老司机可以直接不看了)

 

二、代码范例

      View的部分就直接略过了,看Model部分:

public class Model : INotifyPropertyChanged
{
public string Isbn { get; set; } public string Description { get; set; }
//需要改变的属性值 private string _AS; public string AS { get { return _AS; } set { _AS = value; NotifyPropertyChanged("AS"); } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } }

 

      ViewModel部分:

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
        }
  }

 

小结:

1. Model与ViewModel继承INotifyPropertyChanged

2. 与View有交互的绑定字段需要如下格式:

    private string _a;

    public string a
    {
            get
            {
                return _a;
            }
            set
            {
                _a = value;
                NotifyPropertyChanged("a");
            }
     }

3. 所有命令都为ICommand类型,然后再依照上面的格式通过Delegate完成

4. 写Command类的时候VS会提示你需要哪些方法的,哈哈哈

 

posted on 2017-03-18 16:07  airforce094  阅读(975)  评论(4编辑  收藏  举报