本文的前提是知曉基於Xaml開發,本文以WPF爲例git
一 、簡化屬性通知事件github
普通的屬性通知會寫一個基於INotifyPropertyChanged接口的類this
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寫起來也是比較麻煩的spa
使用Fody/PropertyChanged可省去此麻煩code
項目地址:https://github.com/Fody/PropertyChangedorm
使用方式以下,轉自官方blog
[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:這個屬性是說跳過相等的檢查,沒有實例,我也沒有用過
2、簡化ICommand的綁定事件
若是綁定一個Button 的點擊事件,正常的後臺是寫一個DeletedCommand的屬性
1 private ICommand _clickCommand; 2 3 public ICommand ClickCommand 4 { 5 get { return _clickCommand ?? new DelegateCommand(Click); } 6 set { _clickCommand = value; } 7 } 8 9 10 private Action Click() 11 { 12 throw new NotImplementedException(); 13 }
而後前臺綁定這個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的項目,簡單用一下而已