當在WPF實行MVVM (Model View ViewModel)時, UIElement value 改變時, 總不能於ViewModel 反映到出來, 原因是該Property 沒有fire Changed event.
為方便development, 整了一個base class 作應用如下.
public abstract class BaseViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(PropertyChangedEventArgs e) { if (PropertyChanged != null) { PropertyChanged(this, e); } } /// <summary> /// Call from object when assign value to object. /// </summary> /// <param name="item">property name</param> public void NotifyPropertyChanged(string item) { OnPropertyChanged(new PropertyChangedEventArgs(item)); } }
於ViewModel 內, property 應用如下:
private string _name; public string Name { get { return _name; } set { _name = value; NotifyPropertyChanged("Name"); } }
參考資料:
Leave a Reply