Reputation: 23
In my class I've got an ObservableCollection and I'm listening to its CollectionChanged event. Thing is when I do Fou.ButtonData = an ObservableCollection variable , CollectionChanged event is never called and CreateButtons() never happens. How can I make this work?
Thanks
The code
class Fou
{
private ObservableCollection<string> buttonData;
public ObservableCollection<string> ButtonData
{
get { return buttonData; }
set { buttonData = value; }
}
public Fou()
{
buttonData = new ObservableCollection<string>();
buttonData.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(buttonData_CollectionChanged);
}
void buttonData_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
CreateButtons();
}
}
Upvotes: 2
Views: 4345
Reputation: 755397
From the code sample it looks like the event is never raised because the ObservableCollection<string>
is never actually changed. It is created, it's event assigned to and never actually modified after that. Is there some other code which modifies the collection.
Additionally there is a bug in the setter of ButtonData
. You are allowing another piece of code to change the ObservableCollection<string>
but you are not listening to it's CollectionChanged
event nor are you disconnecting from the previous one. I would make this a readonly property or change it to the following
public ObservableCollection<string> ButtonData
{
get { return buttonData; }
set
{
if (buttonData != null) {
buttonData.CollectionChanged -= buttonData_CollectionChanged;
}
buttonData = value;
if (buttonData != null) {
buttonData.CollectionChanged += buttonData_CollectionChanged;
}
}
}
Upvotes: 4