How to make model class observable in WPF

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 !?

+6
source share
1 answer

If this is not so many times in your code, I would recommend that you make boilerplate code.

Otherwise, you can use this cool code from Ayende to create a proxy class that would automatically execute INotifyPropertyChanged for you (including event collection). Usage will look like this:

 IUser userProxy = DataBindingFactory.Create<User>(); 
+3
source

Source: https://habr.com/ru/post/981044/


All Articles