Silverlight4 + C #: using INotifyPropertyChanged on UserControl to notify another UserControl does not notify
I have several user controls in a project and one of them fetches items from XML, creates objects of type "ClassItem", and needs to notify other UserControl information about those items.
I created a class for my object (the "model" will have all the elements):
public class ClassItem
{
public int Id { get; set; }
public string Type { get; set; }
}
I have another class that is used to notify other custom controls when an object of type "ClassItem" is created:
public class Class2: INotifyPropertyChanged
{
// Properties
public ObservableCollection<ClassItem> ItemsCollection { get; internal set; }
// Events
public event PropertyChangedEventHandler PropertyChanged;
// Methods
public void ShowItems()
{
ItemsCollection = new ObservableCollection<ClassItem>();
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("ItemsCollection"));
}
}
}
The data comes from an XML file that is parsed to create objects of type ClassItem:
void DisplayItems(string xmlContent)
{
XDocument xmlItems = XDocument.Parse(xmlContent);
var items = from item in xmlItems.Descendants("item")
select new ClassItem{
Id = (int)item.Element("id"),
Type = (string)item.Element("type)
};
}
If I'm not wrong this should parse the xml and create a ClassItem object for every item it finds in the XML. Therefore, every time a new ClassItem is created, it should trigger notifications for all UserControls that bind to the “ItemsCollection” notifications defined in Class2.
However, the class 2 code doesn't even run :-( and there are no notifications of course ...
Am I wrong in any assumptions I have made or am I missing something? Any help would be appreciated!
thanks!
a source to share
The property must be available for the notification to work. I don't see any place in the code where you set a value in "ItemsCollection".
I usually follow this pattern:
public ObservableCollection<ClassItem> ItemsCollection
{
get
{
return _itemsCollection;
}
set
{
_itemsCollection= value;
NotifyPropertyChanged("ItemsCollection");
}
}
Then update the ItemsCollection.
//before using the ObservableCollection instantiate it.
ItemsCollection= new ObservableCollection<ClassItem>();
//Then build up your data however you need to.
var resultData = GetData();
//Update the ObservableCollection property which will send notification
foreach (var classItem in resultData)
{
ItemsCollection.Add(classItem);
}
a source to share