您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页WPF中MVVM自动更新

WPF中MVVM自动更新

来源:二三娱乐

前言

讲起WPF,开发模式MVVM是必不可少的,使用MVVM模式以后可以在View中写界面,需要使用到的数据则使用绑定的方式写到标签中,那么控制权就放到了ViewModel中,那么有一个需求是每一个使用MVVM者都会有的,就是在后台改变ViewModel的属性时,同时使前台View绑定的标签内容得到相应更新变动。
定义属性方式对比

传统方式

private string m_Name = "";
public string Name
{
    set
    { 
        if(value!=m_Name){
            m_Name = value; 
            OnPropertyChanged( "Name" ); 
        }
    }
    get { return m_Name; }
}

使用CleanAOP后

public virtual string Name { set; get; }

对比总结:使用传统方式使用了一大堆累赘的代码,使用CleanAOP后,简单、方便。

实战(使用CleanAOP使属性自动更新)

  1. 下载,并且引用dll到项目中。
  2. Notice更新类:
public class Notice : INotifyPropertyChanged, ICommand
{
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                this.PropertyChanged(this, new  PropertyChangedEventArgs(name));
            }

        } 

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

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

        public Func<object, bool> CanExecuteFunc { set; get; }

        public Action<object> ExecuteAction { set; get; }

        }
  1. 定义ViewModel:
[PropertyNotifyIntercept]//添加属性通知标签,表示该类接入属性通知拦截器。
//继承Notice
public class MainWindowVM : Notice
{
      //定义Name属性
      public virtual string Name { set; get; } = "jarvin";
}
  1. 界面上绑定该属性
<TextBox Text="{Binding Name}"></TextBox>
  1. 设置DataContext
public MainWindow()
{
      InitializeComponent();
      this.DataContext = InterceptClassFactory.GetInterceptClass<MainWindowVM>();
}
  1. 修改MainWindowVM的Name的值,这时候界面上会自动做出更新!!

总结

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务