How do I find out who has subscribed to an event field? - c#

I want to find out when the PropertyChanged event handler is set in my base class.
Both Debug.Print("Is Null") and Debug.Print("not null") get hit. So it must get set somewhere.
How do I find that out?
A search for PropertyChanged does not reveal code that subscribes to the ebvent.
public abstract class NonPersistentObjectBase : INotifyPropertyChanged, IObjectSpaceLink {
public event PropertyChangedEventHandler PropertyChanged; // how do I break here
protected void OnPropertyChanged(string propertyName) {
if(PropertyChanged != null) {
Debug.Print("not null"); // gets hit after I click save
}
else {
Debug.Print("Is Null"); //gets hit
}
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected void SetPropertyValue<T>(string name, ref T field, T value) {
if(!Equals(field, value)) {
field = value;
OnPropertyChanged(name);
}
}
I added a private event as per Olivier's suggestion but am unsure how to call it.
I tried assigning it in the constructor
private event PropertyChangedEventHandler PropertyChangedAdd {
add => PropertyChanged += value;
remove => PropertyChanged -= value;
}

We cannot add a breakpoint to such a single statement without an assignment.
We can only add on a runtime instruction.
A void declaration as well as a method signature alone is not an real instruction to be executed: no assignment, no call, no loop, no test, no jump, no calculation... just a "static memory reservation" planned and done by the compiler at compile-time.
But we can implement add and remove accessors of a property-event on a real private field, thus we will be able to put breakpoints.
Also, once that done, we can open the call stack window in Visual Studio or go out of the method toward the caller subscriber.
public event PropertyChangedEventHandler PropertyChanged
{
add => _PropertyChanged += value;
remove => _PropertyChanged -= value;
}
private event PropertyChangedEventHandler _PropertyChanged

Related

WPF: Best way to block OnPropertyChanged

I have implemented WPF data binding with INotifyPropertyChanged.
public class ExportNode : INotifyPropertyChanged
{
public uint Handle { get; set; }
public String Text { get; set; }
private bool _ischecked;
public bool IsChecked
{
get
{
return _ischecked;
}
set
{
_ischecked = value;
OnPropertyChanged("IsChecked");
}
}
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
And than subscribing to event form my code, so whenever I change property in UI, it fires callback.
But now I'm trying to figure out the best way to change property from code, and than not fire callback, just update UI.
void newNode_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsChecked")
{
}
}
For now I just thought about implementing some "blocker" member property in ExportNode
protected void OnPropertyChanged(string name)
{
if (Blocked)
return;
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
or delete event form instance before change.
newNode.PropertyChanged -= newNode_PropertyChanged;
newNode.IsChecked = true;
newNode.PropertyChanged += newNode_PropertyChanged;
But is there any better way? I just don't understand some basics? :-)
Thank you very much
Roman
You've got this a little backwards.
INotifyPropertyChanged, and thus the PropertyChanged event, is what makes the UI update, in fact, its what makes the whole binding system work.
So to update the UI, you have to raise that event. Now, from the code side, you almost never subscribe to that event, because you could just invoke a method from the setter. Something like:
set
{
_ischecked = value;
OnPropertyChanged("IsChecked");
if (!Blocked)
MyOtherMethod();
}
Note that if you are dealing with threads, that Blocked condition is a major synchronization hazard.
If you really need to register for PropertyChanged from code, then your best bet is to just unregister with -=. That way the UI still gets its event, but you don't.

Handling OnPropertyChanged

I'm not well versed in event-based programming. Basically, I'm still stumbling around with it. I'm trying to get something set up, but even with the tutorials, I can't wrap my head around it. What I would like to do (in words) is the following:
I have a dataobject where a property changes. I notice this in the setter of the property, and want to raise an event that the property has changed.
Elsewhere (in a different class entirely), I want to know that the property on this object has changed, and take some action.
Now I'm sure this is a common enough scenario, but my google-fu is letting me down. I'm simply not understanding http://msdn.microsoft.com/en-us/library/ms743695.aspx.
I have this:
public class ChattyClass {
private int someMember;
public event PropertyChangedEventHandler PropertyChanged;
public int SomeMember {
get {
return this.someMember;
}
set {
if (this.someMember != value){
someMember = value;
// Raise event/fire handlers. But how?
}
}
}
public class NosyClass{
private List<ChattyClass> myChatters;
public void addChatter(ChattyClass chatter){
myChatters.add(chatter);
// Start listening to property changed events
}
private void listner(){
// I want this to be called when the PropertyChangedEvent is called
Console.WriteLine("Hey! Hey! Listen! A property of a chatter in my list has changed!");
}
}
What do I do to wire this up?
Concerning the comment pointing me back to the link:
In the example I see:
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
What I'm not understanding:
Why isn't this just calling PropertyChanged(this, new PropertyCHangedEventArgs(name))
Where does PropertyChanged get assigned?
What does the assignment look like?
You have to fire the event. In the example on MSDN, they made a protected method OnPropertyChanged to handle this easier (and to avoid duplicate code).
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
What this method does, is look whether there is an event handler assigned or not (if it is not assigned and you just call it, you'll get a NullReferenceException). If there is one assigned, call this event handler. The event handler provided, has to have the signature of the PropertyChangedEventHandler delegate. This signature is:
void MyMethod(object sender, PropertyChangedEventArgs e)
Where the first parameter has to be of the type object and represents the object that fires the event, and the second parameter contains the arguments of this event. In this case, your own class fires the event and thus give this as parameter sender. The second parameter contains the name of the property that has changed.
Now to be able to react upon the firing of the event, you have to assign an event handler to the class. In this case, you'll have to assign this in your addChatter method. Apart from that, you'll have to first define your handler. In your NosyClass you'll have to add a method to do this, for example:
private void chatter_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine("A property has changed: " + e.PropertyName);
}
As you can see, this method corresponds to the signature I explained before. In the second parameter, you'll be able to find the information of which parameter has been changed. Last thing to do, is add the event handler. Now in your addChatter method, you'll have to assign this:
public void AddChatter(ChattyClass chatter)
{
myChatters.Add(chatter);
// Assign the event handler
chatter.PropertyChanged += new PropertyChangedEventHandler(chatter_PropertyChanged);
}
I would suggest you to read something about events in .NET / C#: http://msdn.microsoft.com/en-us/library/awbftdfh . I think after reading/learning this, things will be more clear to you.
You can find a console application here on pastebin if you would like to test it quickly (just copy/paste into a new console application).
With newer versions of C#, you can inline the call to the event handler:
// inside your setter
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(MyProperty)));
You could also use something like Fody PropertyChanged to automatically generated the necessary code (visit the link to their GitHub page, with samples).
The link that you looked is for the MVVM pattern and WPF. It is not a general C# implementation. You need something like this:
public event EventHandler PropertyChanged;
public int SomeMember {
get {
return this.someMember;
}
set {
if (this.someMember != value) {
someMember = value;
if (PropertyChanged != null) { // If someone subscribed to the event
PropertyChanged(this, EventArgs.Empty); // Raise the event
}
}
}
...
public void addChatter(ChattyClass chatter) {
myChatters.add(chatter);
chatter.PropertyChanged += listner; // Subscribe to the event
}
// This will be called on property changed
private void listner(object sender, EventArgs e){
Console.WriteLine("Hey! Hey! Listen! A property of a chatter in my list has changed!");
}
If you want to know what property has changed you need to change your event definition to:
public event PropertyChangedEventHandler PropertyChanged;
And change the calling to:
public int SomeMember {
get {
return this.someMember;
}
set {
if (this.someMember != value){
someMember = value;
if (PropertyChanged != null) { // If someone subscribed to the event
PropertyChanged(this, new PropertyChangedEventArgs("SomeMember")); // Raise the event
}
}
}
private void listner(object sender, PropertyChangedEventArgs e) {
string propertyName = e.PropertyName;
Console.WriteLine(String.Format("Hey! Hey! Listen! a {0} of a chatter in my list has changed!", propertyName));
}
why isn't this just calling PropertyChanged(this, new
PropertyCHangedEventArgs(name))
Because if no one attached an handler to the event, then the PropertyChanged object returns null. So you'll have to ensure it's not null before calling it.
where does PropertyChanged get assigned?
In the "listener" classes.
For example, you could write in other class:
ChattyClass tmp = new ChattyClass();
tmp.PropertyChanged += (sender, e) =>
{
Console.WriteLine(string.Format("Property {0} has been updated", e.PropertyName));
};
What does the assignment look like?
In C# we use the assignment operators += and -= for events. I recommend reading the following article to understand how to write event handlers using the anonymous method form (example above) and the "old" form.
From taking the original code, and incorporating #Styxxy 's answer, I come out with:
public class ChattyClass : INotifyPropertyChanged
{
private int someMember, otherMember;
public int SomeMember
{
get
{
return this.someMember;
}
set
{
if (this.someMember != value)
{
someMember = value;
OnPropertyChanged("Some Member");
}
}
}
public int OtherMember
{
get
{
return this.otherMember;
}
set
{
if (this.otherMember != value)
{
otherMember = value;
OnPropertyChanged("Other Member");
}
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class NosyClass
{
private List<ChattyClass> myChatters = new List<ChattyClass>();
public void AddChatter(ChattyClass chatter)
{
myChatters.Add(chatter);
chatter.PropertyChanged+=chatter_PropertyChanged;
}
private void chatter_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine("A property has changed: " + e.PropertyName);
}
}

what is the difference between raisepropertychanged and PropertyChanged?

i think both are same,but i found use of them in only one file such as below code.here code for raisepropertychanged .
public decimal Amount
{
get
{
return _amount;
}
set
{
_amount = value;
RaisePropertyChanged("Amount");
}
}
here code for PropertyChanged:
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
// take a copy to prevent thread issues
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
plz explain difference between them:
PropertyChanged is an event. RaisePropertyChanged is the method used to raise the event.
Of course, you could invoke the event directly from your property setter, but then you would have to check every time if the handler is not null... better to do it in one place.

Where does this PropertyChanged event get set?

I am implementing INotifyPropertyChanged and as part of that interface I have the member
public event PropertyChangedEventHandler PropertyChanged;
I have the following code for when some property gets changed -
public string FavoriteColor
{
get { return this.favoriteColor; }
set
{
if (value != this.favoriteColor)
{
this.favoriteColor = value;
**if (this.PropertyChanged != null)**
{
this.PropertyChanged(this, new PropertyChangedEventArgs("FavoriteColor"));
}
}
}
}
Now, I have never set the PropertyChanged variable anywhere in my code, yet if I put a breakpoint at this line it shows that PropertyChanged does have a value. So how is it getting set?
If you bind to the property the binding system subscribes to the event.

Subscribing To The Self Tracking Entities PropertyChanged Event

I am writing a WPF application using Self-Tracking Entities. I'm having trouble Disabling/Enabling my Save button as my Model's values are changed. Normally with the regular Entity Framework Model I am able to simply subscribe to the Model.PropertyChanged event in my ViewModel, then RaisePropertyChanged for my Save Button, which checks validation and Disabled or Enables my save button.
For some reason, with Self-Tracking Entities I noticed that the Model.PropertyChanged event is marked as protected, so I am unable to subscribe to it directly in my ViewModel. Is there any way to subscribe to this event without modifying the T4 Template??
protected virtual void OnPropertyChanged(String propertyName)
{
if (ChangeTracker.State != ObjectState.Added && ChangeTracker.State != ObjectState.Deleted)
{
ChangeTracker.State = ObjectState.Modified;
}
if (_propertyChanged != null)
{
_propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
protected virtual void OnNavigationPropertyChanged(String propertyName)
{
if (_propertyChanged != null)
{
_propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged{ add { _propertyChanged += value; } remove { _propertyChanged -= value; } }
private event PropertyChangedEventHandler _propertyChanged;
private ObjectChangeTracker _changeTracker;
I've always just modified the template to make it not protected. It's a template for a reason :)
I suppose an alternative would be to create a public method on your class which raises the PropertyChanged notification internally.
partial class MyModel
{
public RaiseEFPropertyChanged(string propertyName)
{
RaisePropertyChanged(propertyName);
}
}

Categories

Resources