WPF中MVVM自動更新

CleanAOP介紹:https://github.com/Jarvin-Guan/CleanAOP

前言

講起WPF,開發(fā)模式MVVM是必不可少的,使用MVVM模式以后可以在View中寫界面,需要使用到的數(shù)據(jù)則使用綁定的方式寫到標簽中,那么控制權(quán)就放到了ViewModel中,那么有一個需求是每一個使用MVVM者都會有的,就是在后臺改變ViewModel的屬性時,同時使前臺View綁定的標簽內(nèi)容得到相應(yīng)更新變動。
定義屬性方式對比

傳統(tǒng)方式

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

對比總結(jié):使用傳統(tǒng)方式使用了一大堆累贅的代碼,使用CleanAOP后,簡單、方便。

實戰(zhàn)(使用CleanAOP使屬性自動更新)

  1. 下載CleanAOP2.0.0,并且引用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. 設(shè)置DataContext
public MainWindow()
{
      InitializeComponent();
      this.DataContext = InterceptClassFactory.GetInterceptClass<MainWindowVM>();
}
  1. 修改MainWindowVM的Name的值,這時候界面上會自動做出更新!!

總結(jié)

感謝大家使用CleanAOP,使用該方式也可以綁定命令,綁定命令的方式在Demo中會有展示,希望能給大家?guī)矸奖恪4蠹铱梢?a target="_blank" rel="nofollow">下載Demo來調(diào)試。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容