Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write less boilerplate for property changed notifications? [duplicate]

Tags:

c#

mvvm

wpf

I've got a MVVM-ish application which ended up with a model with way too many property change notifications. Specifically, I'm sometimes missing some notifications because there's too many of them.

For example I end up with properties like this:

public string CustomEmail {
    get => customEmail;
    set
    {
        customEmail = value;
        OnChanged("CustomEmail");
        OnChanged("IsSendAllowed");
        OnChanged("IsNotFaxEmail");
    }
}

Is there a better way to organise it? For example is there a way to mark a property [DependsOn("CustomEmail")] bool IsNotFaxEmail { ... }?

Or if most of the properties are used for bindings, should I be going all in on converters instead? I'd rather not end up with a silly number of converters like {Binding CustomEmail, Converter=EmailIsFaxToElementVisibilityConverter}.

Am I missing some simpler solution?

like image 929
viraptor Avatar asked Dec 05 '22 07:12

viraptor


1 Answers

I don't often find so many dependencies but I can outline a solution I've seen. Create an attribute. Call it AlsoRaise attribute which takes a string parameter. You can probably think of a better name. But I think dependson isn't quite right because it's the other way round.

[AlsoRaise(nameof(IsSendAllowed))]
[AlsoRaise(nameof(IsNotFaxEmail))]
public string CustomEmail

You then have something can drive your list of other properties you're going to raise change notification for as well as CustomEmail.

In a static constructor you fill a dictionary<string, string[]> using those attributes. You iterate public properties, grab those attributes.

In OnChanged you look up your property name in that dictionary and raise property changed for the property name plus any strings you find. Or none of course.

I may have forgotten some part, while since I saw this implementation.

like image 121
Andy Avatar answered Dec 11 '22 09:12

Andy