用開源AOP簡化MVVM框架
本文的前提是知曉基于Xaml開發,本文以WPF為例
一 、簡化屬性通知事件
普通的屬性通知會寫一個基于INotifyPropertyChanged接口的類
1 public class RasiePropertyChanged : INotifyPropertyChanged 2 { 3 public event PropertyChangedEventHandler PropertyChanged; 4 5 protected void OnPropertyChanged([CallerMemberName]string propertyName = null) 6 { 7 PropertyChangedEventHandler handler = PropertyChanged; 8 if (handler != null) 9 { 10 handler(this, new PropertyChangedEventArgs(propertyName)); 11 } 12 } 13 14 }
這樣用時就可以在屬性的Set里最后加上一句RasiePropertyChanged();就可以,但是如果屬性只是簡單的Get,Set寫起來也是比較麻煩的
使用Fody/PropertyChanged可省去此麻煩
項目地址:https://github.com/Fody/PropertyChanged
使用方式如下,轉自官方
[ImplementPropertyChanged] public class Person { public string GivenNames { get; set; } public string FamilyName { get; set; } public string FullName { get { return string.Format("{0} {1}", GivenNames, FamilyName); } } }
在類上邊寫上一個Attribute [ ImplementPropertyChanged],類里的所有屬性就都實現了屬性通知事件
DoNotNotify:如果有某個屬性不想實現通知事件,就在相應屬性上加個[DoNotNotify]
AlsoNotifyFor: 如果有某個屬性像上邊的FullName一樣是2個屬性的組合,任何一個變化都要通知都FullName變化,就在子屬性GivenNames 和FamilyName上加個[ AlsoNotifyFor("FullName")]
DependsOn: 如果反過來FullName變了也讓子屬性變化,那就要在FullName上加上 [DependsOn("GivenName","FamilyName")]
DoNotSetChanged:這個屬性是說當FullName 的Set改變時,不會通知到子屬性
DoNotCheckEquality:這個屬性是說跳過相等的檢查,沒有實例,我也沒有用過
二、簡化ICommand的綁定事件
如果綁定一個Button 的點擊事件,正常的后臺是寫一個DeletedCommand的屬性
1 private DelegateCommand _clickCommand; 2 3 public DelegateCommand ClickCommand 4 { 5 get 6 { 7 return _clickCommand; 8 } 9 set 10 { 11 if (_clickCommand == null) 12 { 13 _clickCommand = new DelegateCommand(Click()); 14 } 15 else 16 { 17 _clickCommand = value; 18 } 19 } 20 } 21 22 [OnCommand("ClickCommand")] 23 private Action Click() 24 { 25 throw new NotImplementedException(); 26 }
然后前臺綁定這個ClickCommand使用Fody/Commander.Fody可省去寫ICommand的屬性
項目地址:https://github.com/DamianReeves/Commander.Fody
使用方式如下,轉自官方
1 [OnCommand("ClickCommand")] 2 private Action Click() 3 { 4 throw new NotImplementedException(); 5 }
如此就可以了
但是ICommand接口有2個方法,一個是 Execute,一個是 CanExecute
所以屬性自然也是有2個,分別對應這2個方法 OnCommand , OnCommandCanExecute
如有問題請參照項目說明和示例,本人只是恰巧看到了這2個簡單的Fody的項目,簡單用一下而已