Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a model class observable in WPF

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

like image 229
Seven Avatar asked Jan 15 '15 11:01

Seven


People also ask

What is ObservableCollection in WPF?

WPF provides the ObservableCollection<T> class, which is a built-in implementation of a data collection that implements the INotifyCollectionChanged interface.

What is INotifyPropertyChanged in WPF?

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 .


1 Answers

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>();
like image 79
Moti Azu Avatar answered Sep 16 '22 13:09

Moti Azu