Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObservableCollection does not raise property changed with Fody

I have defined this class

[ImplementPropertyChanged]
public class ChatInfo : IMessageData
{
    public ObservableCollection<Message> messages { get; set; }

    [JsonIgnore]
    public Message LastMessage
    {
        get
        {
            return messages.Last();
        }
    }
}

The class is deserialized via JSON.NET(James King) and then after I manually pushing new items to messages. The LastMessage property is bound to a view, but even if messages collection changes, LastMessage getter is not called. When I set messages to new collection every time, everything works fine, why doesn't LastMessage react to collection changed events from ObservableCollection?

like image 724
Aldos Avatar asked Oct 22 '25 07:10

Aldos


1 Answers

LastMessage does not react on collection change because message remain the same. You need to subscribe to the event of your observable collection.

[ImplementPropertyChanged]
public class ChatInfo : IMessageData
{
  public ObservableCollection<Message> messages { get; set; }

  messages.CollectionChanged += new
  System.Collections.Specialized.NotifyCollectionChangedEventHandler(MessageChanged);

  [JsonIgnore]
  public Message LastMessage {get; private set;}


  private void MessageChanged(object sender, NotifyCollectionChangedEventArgs e) 
  {
   //set the property here
   LastMessage = messages.Last();
  }
}
like image 133
LeBaptiste Avatar answered Oct 23 '25 21:10

LeBaptiste



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!