모델(Model) 객체에 대해 OneWay 혹은 TwoWay 바인딩을 지원하기 위해서는 속성 변경 알림이 구현되어야 합니다.
using System.ComponentModel;
namespace SDKSample
{
// This class implements INotifyPropertyChanged
// to support one-way and two-way bindings
// (such that the UI element updates when the source
// has been changed dynamically)
public class Person : INotifyPropertyChanged
{
private string name;
// Declare the event
public event PropertyChangedEventHandler PropertyChanged;
public Person()
{
}
public Person(string value)
{
this.name = value;
}
public string PersonName
{
get { return name; }
set
{
name = value;
// Call OnPropertyChanged whenever the property is updated
OnPropertyChanged("PersonName");
}
}
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
}
How to: Implement Property Change Notification
MSDN Library
위 코드를 매번 구현하면 중복된 코드도 많아지고, 매우 귀찮습니다.
하여 ModelBase 클래스를 구현한 후 상속해 쓰도록 할 수 있습니다.
아래 코드는 GalaSoft.MvvmLight.ViewModelBase 코드를 참고하였습니다.
using System.Runtime.CompilerServices;
using System.ComponentModel;
public class ModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if(handler == null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
protected bool Set<T>(ref T field, T newValue = default(T), [CallerMemberName] string propertyName = null)
{
field = newValue;
if(propertyName != null)
{
OnPropertyChanged(propertyName);
return true;
}
return false;
}
}
이렇게 되면 코드는 아래와 같이 바뀝니다.
namespace SDKSample
{
public class Person : ModelBase
{
private string name;
public Person()
{
}
public Person(string value)
{
this.name = value;
}
public string PersonName
{
get { return name; }
set
{
Set(ref name, value);
}
}
}
}
Easy MVVM Example With INotifyPropertyChanged And INotifyDataErrorInfo
Darko Micics Development Blog
