ericpap
ericpap

Reputation: 2937

Is there a better way to write this code on ViewModel?

Beeing new at MVVM and WPF, I found myself writing tons of code almost identical in my ViewModel to expose properties and then bind on my WPF controls. Something like this:

private Vendedores _vendedorsel;
public Vendedores VendedorSel
    {
        get
        {
            return _vendedorsel;
        }

        set
        {
            this._vendedorsel = value;
            OnPropertyChanged("VendedorSel");
        }
    }

Is there a better way to do this, without having so much similar code? maybe something that involves inheritance? Thank you.

Upvotes: 2

Views: 66

Answers (2)

ericpap
ericpap

Reputation: 2937

I Found an excelent answer to this problem in this great Blog. I Couldn't understand why I need to fire OnPropertyChanged from every property on every setter and why I can't use an auto-implemented property like this on my ViewModel:

public Vendedores VendedorSel {get; set;}

And the point show in the blog above is that in 95% of cases you can!!! Why?: Because The only reason to fire OnPropertyChanged is if the property is modify OUTSIDE the scope of the view and to inform to it "hey! this property change! please update yourself" But in the majority on cases the property is only Modify within the view! in this case is OnPropertyChange is not need!!

Even more! I could even set a default value for the property on the ViewModel Contructor and still don't need to fire OnPropertyChanged because the contructor is executed BEFORE the binding is made. This whille drastically reduce my code of repetitive unneeded manual defined properties! So Thanks to anybody!

Upvotes: 1

John Bowen
John Bowen

Reputation: 24453

You can trim this down a little by using CallerMemberName in your base method, which also make refactoring easier if you ever rename the property:

protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
    PropertyChangedEventArgs ea = new PropertyChangedEventArgs(propertyName);
    if (PropertyChanged != null)
        PropertyChanged(this, ea);
}

This cuts your property code down to:

public Vendedores VendedorSel
{
    get
    {
        return _vendedorsel;
    }    
    set
    {
        this._vendedorsel = value;
        OnPropertyChanged();
    }
}

You can get similar gains by using frameworks as mentioned by Geek's answer but still need some amount of the boilerplate in most cases. Aspect oriented programming can be used to inject all this stuff for you onto even auto-properties but that can also be a lot to take on if you're not doing anything else with AOP.

Usually the best thing to make this less painful is some good snippets to generate the boilerplate for you.

Upvotes: 1

Related Questions