Scenario
I get a model class from an external component or a code part where I do not want to alter something. I'd like to bind this class to some WPF UI. I also would like to refresh the UI if this model gets altered.
Question
Do I really need to write a wrapper class all the time, that creates PropertyChanged events for each setter? How could I prevent to write all this clue coding manually?
What started like this ...
public class User : IUser
{
public String Name { get; set; }
public bool CurrentlyLoggedIn { get; set; }
// ...
}
... will always be bloated like so
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 ) );
}
}
}
There must be a more intelligent way of doing that!?
WPF provides the ObservableCollection<T> class, which is a built-in implementation of a data collection that implements the INotifyCollectionChanged interface.
The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed. For example, consider a Person object with a property called FirstName .
If it doesn't happen a lot of times in your code I would recommend you to do the boilerplate code.
Otherwise, you can use this cool piece of code from Ayende to generate a proxy class that would auto implement INotifyPropertyChanged
for you (including event raising).
Usage would look like this:
IUser userProxy = DataBindingFactory.Create<User>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With