Reputation: 50687
I have a collection of data defined as follows (MyData
is defined as a class):
ObservableCollection<MyData> data = new ObservableCollection<MyData>();
I bind it with another function called another_func()
whenever the its data changes by:
data.CollectionChanged += data_CollectionChanged;
...
void data_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
another_func();
}
It worked well if I just add or remove elements from data
, i.e. it will call another_func()
automatically whenever these operations happen.
However, it didn't work (not trigger another_func()
) when I try to assign values to data
, for example:
data = another_data; // another_data also with type ObservableCollection<MyData>
Why can't this handle assignment event? And how to make it work?
Upvotes: 0
Views: 162
Reputation: 1855
Its because you did not change observable collection, you just change reference to which "points" data variable. CollectionChanged event fires ObservableCollection object on every change (insert, remove, ...), but it does not fire event in this situation because you did not change actual object.
If you want event to be fired try something like (it may fire event more than once)
data.Clear();
foreach (var obj in another_data)
{
data.Add(obj);
}
If you need to notify all observers on reference swap, one of many ways can be to make subclass of observablecollection class (because OnCollectionChanged method is protected):
class SomeOtherClass<T> : ObservableCollection<T>
{
public void InvokeAllOnChangedObservers()
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); // or OnCollectionChanged(null);
}
}
static void Main(string[] args)
{
SomeOtherClass<string> a = new SomeOtherClass<string>();
a.CollectionChanged += (sender, evnt) =>
{
Console.WriteLine("Handler");
};
a.InvokeAllOnChangedObservers(); // prints handler
}
You could also create event, on which object subscribes, to your base class (which hold observablecollection) and notify all subscribers with that event. Your class, in that case, need to subscribe to ObservableCollection CollectionChanged event and resend received args to all subscribers...
You could also look at this example and try if that can be used in your case
Upvotes: 2