Ales
Ales

Reputation: 193

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?

Upvotes: 4

Views: 2157

Answers (1)

LeBaptiste
LeBaptiste

Reputation: 1186

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();
  }
}

Upvotes: 4

Related Questions