码迷,mamicode.com
首页 > Windows程序 > 详细

wpf的mvvm

时间:2020-09-14 18:49:43      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:ane   serial   prope   调用   class   执行命令   hang   fun   invoke   

INotifyPropertyChanged,用来绑定字段

/// <summary>
    /// mvvm的基类
    /// </summary>
    public class NotificationOjbect : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void RaisePropertyChanged(string PropertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(PropertyName));
            }
        }
    }

ICommand,用来绑定事件

    /// <summary>
    /// 执行命令
    /// </summary>
    public class DelegateCommand : ICommand
    {
        public event EventHandler CanExecuteChanged;
        public Action<object> ExecuteAction;
        public Func<object, bool> CanExecuteFunc;

        public DelegateCommand()
        {

        }

        public DelegateCommand(Action<object> execute) : this(execute, null)
        {
        }

        public DelegateCommand(Action<object> execute, Func<object, bool> canExecute)
        {
            if (execute == null)
            {
                return;
            }
            ExecuteAction = execute;
            CanExecuteFunc = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            if (this.CanExecuteFunc == null)
            {
                return true;
            }
            return this.CanExecuteFunc(parameter);
        }

        public void Execute(object parameter)
        {
            if (this.ExecuteAction != null)
            {
                this.ExecuteAction(parameter);
            }
        }
    }

属性的绑定

 private string _PortName;
        /// <summary>
        /// 端口名称
        /// </summary>
        public string PortName
        {
            get { return _PortName; }
            set
            {
                _PortName = value;
                _notification.RaisePropertyChanged("PortName");
            }
        }

事件的绑定

public ICommand SaveSerialPort
        {
            get
            {
                return new DelegateCommand(
                    (param) =>
                    {
                        btnSave_Click(param);
                    }
                   , (v) => { return true; });
            }
        }

调用代码

this.DataContext = new SerialPortViewModel();

界面绑定属性和事件

技术图片

 

一个最简单的wpf的mvvm就弄完了

技术图片

dome的地址:https://gitee.com/cainiaoA/wpfstudent

 

wpf的mvvm

标签:ane   serial   prope   调用   class   执行命令   hang   fun   invoke   

原文地址:https://www.cnblogs.com/shuaimeng/p/13594745.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!