Handling OnPropertyChanged

前端 未结 4 1497
南笙
南笙 2020-12-07 16:12

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 w

相关标签:
4条回答
  • 2020-12-07 16:27

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-07 16:33

    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));
       }
    
    0 讨论(0)
  • 2020-12-07 16:33

    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.

    0 讨论(0)
  • 2020-12-07 16:37

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

    0 讨论(0)
提交回复
热议问题