Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

c# - 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:

  1. 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.

  2. 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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...