CleanAOP介紹:https://github.com/Jarvin-Guan/CleanAOP
前言
講起WPF袋坑,開發(fā)模式MVVM是必不可少的亿笤,使用MVVM模式以后可以在View中寫界面,需要使用到的數(shù)據(jù)則使用綁定的方式寫到標(biāo)簽中玉罐,那么控制權(quán)就放到了ViewModel中腋逆,那么有一個需求是每一個使用MVVM者都會有的偶宫,就是在后臺改變ViewModel的屬性時,同時使前臺View綁定的標(biāo)簽內(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后砂心,簡單、方便蛇耀。
實(shí)戰(zhàn)(使用CleanAOP使屬性自動更新)
- 下載CleanAOP2.0.0,并且引用dll到項(xiàng)目中辩诞。
- 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; }
}
- 定義ViewModel:
[PropertyNotifyIntercept]//添加屬性通知標(biāo)簽,表示該類接入屬性通知攔截器纺涤。
//繼承Notice
public class MainWindowVM : Notice
{
//定義Name屬性
public virtual string Name { set; get; } = "jarvin";
}
- 界面上綁定該屬性
<TextBox Text="{Binding Name}"></TextBox>
- 設(shè)置DataContext
public MainWindow()
{
InitializeComponent();
this.DataContext = InterceptClassFactory.GetInterceptClass<MainWindowVM>();
}
- 修改MainWindowVM的Name的值译暂,這時候界面上會自動做出更新!撩炊!
總結(jié)
感謝大家使用CleanAOP,使用該方式也可以綁定命令外永,綁定命令的方式在Demo中會有展示,希望能給大家?guī)矸奖闩】取4蠹铱梢?a target="_blank" rel="nofollow">下載Demo來調(diào)試伯顶。