[WPF] 如何令ViewModel property 實現Tow-way binding

當在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");
    }
}

參考資料:

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.