Scenario
I get a model class from an external component or piece of code where I don't want to change anything. I would like to bind this class to some WPF interface. I would also like to update the user interface if this model is changed.
Question
Do I really need to write a wrapper class all the time, which creates PropertyChanged events for each setter? How can I prevent all this key code from being written manually?
What started like this ...
public class User : IUser { public String Name { get; set; } public bool CurrentlyLoggedIn { get; set; }
... will always swell like that
public class UserObservableWrapper : IUser, INotifyPropertyChanged { public String Name { get { return this.innerUser.Name; } set { if (value == this.innerUser.Name) { return; } this.innerUser.Name = value; this.OnPropertyChanged( "Name" ); } } public bool CurrentlyLoggedIn { get { return innerUser.CurrentlyLoggedIn; } set { if (value.Equals( innerUser.CurrentlyLoggedIn )) { return; } innerUser.CurrentlyLoggedIn = value; this.OnPropertyChanged( "CurrentlyLoggedIn" ); } } private readonly IUser innerUser; public UserObservableWrapper( IUser nonObservableUser ) { this.innerUser = nonObservableUser; } public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged( string propertyName ) { PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { handler( this, new PropertyChangedEventArgs( propertyName ) ); } } }
Should there be a smarter way to do this !?
Seven source share