I have a class that needs to call a method NotifyPropertyChanged
when any of its properties are changed. What I've seen in examples is something like:
private string property1_;
public string Property1
{
get { return property1_; }
set { property1_ = value; NotifyPropertyChanged(); }
}
private string property2_;
public string Property2
{
get { return property2_; }
set { property2_ = value; NotifyPropertyChanged(); }
}
// .......
Is this really the idiomatic way to do it? It requires several lines of boilerplate for every property I want to add. Moreover, if I want to change the name of the property and field, I would need to change 4 different things. It seems like a violation of DRY.
Getter and setter methods (also known as accessors) are dangerous for the same reason that public fields are dangerous: They provide external access to implementation details. What if you need to change the accessed field's type? You also have to change the accessor's return type.
If you want to use JavaScript getter/setter with the same name as the properties, e.g. to intercept certain setters to implement side effects, you can create a Proxy for your object.
Getters and Setters in python are often used when: We use getters & setters to add validation logic around getting and setting a value. To avoid direct access of a class field i.e. private variables cannot be accessed directly or modified by external user.
Given this, getters and setters are also known as accessors and mutators, respectively. By convention, getters start with the word "get" and setters with the word "set", followed by a variable name.
Yes, this is the idiomatic way to raise PropertyChanged
. There's no easy way around it, since the setter needs an additional method call and the only way to do that is with a full property and backing field.
It actually used to be worse, as before .NET 4.5 you had to pass the property name as a string to "NotifyPropertyChanged", so changing the name is actually quite a bit easier now.
That said, there are frameworks (MVVMLight, Caliburn.Micro) that will inject the event raise for you if you choose to use them. Of course, they are just giving you a little syntatic sugar, and the end result is the same.
You might want to try using an AOP framework to implement your INotifyPropertyChanged
. My personal favourite for this example is called Fody.
You would write the class like this...
[ImplementPropertyChanged]
public class Foo
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
Fody works by rewriting your dll after MsBuild is done with it, to implement your INPC code.
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