INotifyPropertyChanged on all properties - c#

Considering a class with a large number of properties, I want to implement a Dirty flag (in order to know if I should update the value in the database).
Is there any way to raise PropertyChanged on All the properties without having to manually go through and pluck it in the setter?
Edit to clear up some things: I did go through the thread that was linked here, and found some things, but unfortunately they do not suit my need. I don't really need to send an event, I just need to flip a flag. Also, that thread is quite old, and I hoped that maybe with C# 7 something came out which would help with it, that I missed in the changelog.
Why don't I just go and do it manually? Well, I might have to. But I'd have to declare the "hidden" variables, manage the code myself, I hoped MS would've done something to help, maybe something like was suggested in the other topic
public Type Name {get; set; notify { () => IsDirty = true; }}
that would help a lot (ignoring the fact it would ask me to declare the get and set anyways because they're abstract.

Add a method that looks like this:
public void Test()
{
if(PropertyChanged != null)
PropertyChanged(new PropertyChangedEventArgs(null));
}
Passing a null or empty string as the property name tells consumers that all properties have been changed.
https://msdn.microsoft.com/en-us/library/system.componentmodel.propertychangedeventargs.propertyname(v=vs.110).aspx

You can but its also a lot of work. Make an Attribute and use it on those properties. in the base class of your ViewModel,
which will implement INotifyPropertyChanged,
You register in its Constructor to the PropertyChanged event and check via reflection if the property that changed has your attribute on it,
and then set IsDirty accordingly.

Related

Is there a way to perform an action every time an object changes state?

I have an object that gets passed to an interface, I would like for the concrete sitting behind that interface to perform some action every time one of the object's members changes state. In other words, I have some object that contains an integer. When the value of that integer changes, I would like for my concrete class sitting behind that interface to do some work.
Now, I could probably do something like this by having a thread that's sitting in the wait state and performs the action once some pulse is done using a monitor. But, I was wondering if the C# language had the inherent support for such a thing. Such that, when the object's member changes state the action will automatically be performed. I know that this may not be possible, and if there is an alternative solution I would like to hear that. Or, does the thread thing sound like a good idea?
You should implement INotifyPropertyChanged, also inherit your interface after INotifyPropertyChanged. Then introduce properties for all state ralated things and always in setter methods fire PropertyChanged event.
This requires some boilerplate code but it is very reliable solution. You can make your properties virtual and use IoC containers such as Unity to implement boilerplate for you.
After the implementation is done you simply subscribe to PropertyChanged event of object by using += operator.
myWatchedObject.ProperyChanged += listener.DependentObjectChangeHandler;
Encapsulate state of an object using a setter property.
Add more code to the setter property to raise an event or call a method.
The simplest way would be properties:
class MyClass
{
private int _MyInteger;
public int MyInteger
{
get { return _MyInteger; }
set { _MyInteger = value; /* insert your "do some work" code here */ }
}
}

Should you reference the Property or the Member Variable inside a class? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Should you access a variable within the same class via a Property?
I ran into this recently and was curious if there was some sort of standard for which one you should reference while inside a class.
I mean really it shouldn't make a difference whether you access the member variable directly or go through the property (unless you need to dodge some custom setter code), but I wanted to be sure there wasn't a best practice for it.
partial class MyClass {
private string foo;
internal string Foo {
get {
return foo;
}
private set {
foo=value;
// I do other stuff
}
}
public void DoSomething() {
//Option 1;
Foo="some string";
//Option 2;
foo="some string";
}
}
This shouldn't be a choice you really make. Either the code in the setter is supposed to run, in which case use the property, or it's not, in which case you use the member variable. In most all situations one is right and one is wrong. Neither is always right/wrong in the general case, and it's unusual for it to "not matter".
For example, if the setter code is firing a "changed" event, do you want external objects to be notified that it changed, or not? If you're changing it in response to a previous change, probably not (infinite recursion anyone?) if no, you probably want to make sure it's fired (so that you're not changing a value and not notifying anyone of changes).
If it's just validating that the value being set is valid, then either you know that, in this context, the value is already validated and must be valid, in which case there is no need to validate again; set the property. If you haven't yet validated what you're about to set then you want the validation logic to run, so use the property.
This question is quite a lot debated, so there is no obvious answer to the question.
Personally I prefer to access via the property because you might have some validation or conversion code in it. Even though your getters and setters are trivial, they might change in the future.
If you wrapped the field foo in the property Foo, you probably did so for a reason (conversion, events, validation, etc). So, generally speaking, the only place you should be referencing the field foo is in the getters and setters for the property Foo. The rest of the code should reference the property Foo.
I'm sure there exists some obscure situation where you would need to bypass the property's getters and setters, and that's certainly okay to do, but such situations would be the exception to the rule.
Option 1 is good practice. because if you use the Option 2, you will lose other stuff when setting the foo value.
I would go with Option 1. If you're setting a variable, you should use the property and not access the variable directly. This is because the property has the extra code you indicated with "// I do other stuff". You wouldn't want to have to repeat this "other stuff" just because you didn't set the property...unless, you don't want to do "other stuff" when you're setting it this time.
Honestly, this is just a theoretical situation, and it would be a lot easier to answer if you give a practical situation where you encounter this problem.
When using the INotifyPropertyChanged interface, using the property is a must, if you wish to update binded objects.
If the setter doesn't have a logic there is no point in explicitly declaring the private variable and it's better to use auto-implemented properties:
internal string Foo
{
get;
private set;
}
public void DoSomething()
{
this.Foo = "some string";
}
If the setter has a logic, the private variable should only be used in the setter and never be modified outside of the setter.
In any case (and in my opinion :)) a private variable should never appear anywhere else beside the property setter.
Imagine the code like
public partial class HybridPanel: Panel {
[DefaultValue(BorderStyle.FixedSingle)]
public virtual new BorderStyle BorderStyle {
set {
if(value!=borderStyle) {
borderStyle=value;
base.PerformLayout();
}
}
get {
try {
return borderStyle;
}
finally {
if(borderStyle!=base.BorderStyle)
base.PerformLayout();
}
}
}
BorderStyle borderStyle=BorderStyle.FixedSingle;
bool isCollapsed, isAutoSize;
}
In this conext, the property is not only used as a variable, but also other things to do.
Access the properties in the same class is NOT considered a bad pratice, further, the complier would suggest that:
A method that is just for access a field without passing arguments, consider define as a property instead.
By the way, you might correct the description of access the member variable directory to be access the member variable directly(that is, access with the fields).

How to update Dependent Property when a property value changes?

I have class that has two properties
public List<ChildMember> ChildMember
{
get
{
if (_ChildMember == null)
{
_ChildMember = this.UserRole == EUserRole.SalesExecutive ? this.GetMembers(this.LogonName, this.FilterByMID) : this.GetChildMembers();
}
return _ChildMember;
}
set
{
_ChildMember = value;
}
}
public int FilterByMID{ get; set; }
Essentially what I need to do is refresh the ChildMember list every time FilterByMID value is changed. I know I can set the this.ChildMember = null before updating the value of FilterByMID but I was wondering if this would be a good place to use INotifyPropertyChanged or perhaps a better way? Any help would be appreciated.
P.S.: GetMembers() method has the logic to check for 0s and -ve values in case it is bothering you :)
P.S.: This class lives in a class library but is used by ASP.NET WebApplication not WCF/WPF ... I noticed a lot of posts for WCF / WPF when I was searching for INotifyPropertyChanged so just wanted to clarify.
If you're only doing this once in this class I wouldn't mind bringing in INotifyPropertyChanged as you would have to make the notification in your setter for FilterByMID and then wire up an event handler in which you'd update the other property.
However, if you have multiple classes and instances needing to observe changes in properties on each other, it might be a more suitable way.
There're also some frameworks which are interesting in this regard. Some examples are the Reactive Extensions, Rx.NET, and the (built on the former) Reactive UI, which has a component not only suitable for user interface programming.
You should just clear the field in the FilterByMyID setter.
INotifyPropertyChanged allows you to notify someone else that a property changed.
Using it directly within your class will just make your code more complicated.

Binding a (complex) class property to CF.NET in C#

I am trying to make a 2-way binding of a class property.
public class MyClass{
public MyField AField1{get;set;};
public MyField AField2{get;set;};
}
public class MyField{
public string Value {get; set}
}
MyClass _class = MyClass();
_dv.DataSource = _class;
Databinding text object displays MyField class name instead of Value Property. I also tried to enter:
DataMember = "AField1.Value";
Is there any way to bind (2-way) AField1.Value of a class MyClass to a visual control?
It's a pain. There's no built-in way to achieve this in .NET, so I can safely say, even less in the CF.
You can get started with this article on MSDN Blogs, but it's pretty limited as you can only get one level of nested property bindings.
Personnally, I ended up writing a custom BindingSource, based on code that lies somewhere on the internets. I can't give you source code of my rewrite as it's property of my employer, but here's the link to the project that got me started.
There are a few drawbacks to the code provided : some of his namespaces are System.ComponentModel, and VS2010 didn't seem to like, so I had to rename them. And a few more issues in design time that can make it a pain to use (so you'll want to fix that too), like loosing the list of properties when you make a spelling mistake and so on...
But it's the best shot (IMHO) at creating a good BindingSource that handles nested objects, and you'll get the idea of what needs to be done to achieve your nested bindings.
The last drawback (and biggest probably, but I have no experience with CF) is that the project is written for the regular .NET Framework, so it's likely that you will have to rewrite it entirely.
Hope that helps....
Edit. Uh oh, I've been grave-digging without noticing... sorry.
PS. Another idea is to simply create one binding source for each of your nested objects, but it gets messy (IMO) if your object hierarchy is complex.

PropertyInfo.AddValueChanged Equivalent for Fields?

I'm trying to find the equivalent of PropertyInfo.AddValueChanged for FieldInfo. I basically just need to receive an event any time the field's value changes. I'm assuming there's nothing like this and I'll have to manipulate IL code or something like that. I'm willing to go that route, but any suggestions on how I should go about it? And is there an AddValueChanged equivalent for fields that I'm not aware of so I don't have to go that route?
Thanks.
Why not just wrap the field in a property, and implement an event on change (ie: make your class INotifyPropertyChanged or your own equivelent)?
That's one the beautiful things about properties - they allow you to define behavior in this manner. Fields do not have any equivelent, and manipulating IL is not going to change this. As long as it's a field, it will not notify.
Let me just confirm that there's nothing built-in like what you're after. Properties can easily implement that because the setter is a method, while fields by design don't have setter methods, their value is just modified and that can happen from any place in the code. To do what you're after, I think you could take a look at PostSharp.
As indicated in the other answers, with the limited information you provided, I would suggest you make any value assignments via the field's accessor. If it needs to be outside of any class, you can create a separate class (or struc) (and put your field change in an accessor.) If you do not need multiple instances of the field, you can declare it static and only access it via its accesor.
Are you exposing public fields that you are trying to monitor? It seems like you should wrap them in properties and expose them that way. Then you can use the monitoring code you've already got.

Categories