首页 > 代码库 > WPF后台通知前台事件(ViewModelBase记录)

WPF后台通知前台事件(ViewModelBase记录)

版本1:

定义:
public class ModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } 引用: public class Person : ViewModelBase { private string _Name; /// <summary> /// 名字 /// </summary> public string Name { get { return _Name; } set { _Name = value; RaisePropertyChanged("Name"); } } }

版本2:

定义:
public class ViewModelBase : INotifyPropertyChanged
    {
        protected void RaisePropertyChanged<T>(Expression<Func<T>> action)
        {
            var propertyName = GetPropertyName(action);
            RaisePropertyChanged(propertyName);
        }

        private static string GetPropertyName<T>(Expression<Func<T>> action)
        {
            var expression = (MemberExpression)action.Body;
            var propertyName = expression.Member.Name;
            return propertyName;
        }

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

        public event PropertyChangedEventHandler PropertyChanged;
    }
引用:
public class Person : ViewModelBase
    {
        private string _Name;
        /// <summary>
        /// 名字
        /// </summary>
        public string Name
        {
            get { return _Name; }
            set
            {
                _Name = value;
                RaisePropertyChanged(() => Name);
            }
        }
    }

 

WPF后台通知前台事件(ViewModelBase记录)