【发布时间】:2026-01-03 01:10:01
【问题描述】:
我在一个项目中有几个用户控件,其中一个从 XML 中检索项目,创建“ClassItem”类型的对象,并且应该通知其他用户控件有关这些项目的信息。
我为我的对象创建了一个类(所有项目都将具有的“模型”):
public class ClassItem
{
public int Id { get; set; }
public string Type { get; set; }
}
我有另一个类,用于在创建“ClassItem”类型的对象时通知其他用户控件:
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"));
}
}
}
数据来自一个 XML 文件,该文件被解析以创建 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)
};
}
如果我没记错的话,这应该是解析 xml 并为它在 XML 中找到的每个项目创建一个 ClassItem 对象。因此,每次创建新的 ClassItem 对象时,都应该为所有“绑定”到 Class2 中定义的“ItemsCollection”通知的用户控件触发通知。
然而 Class2 中的代码甚至似乎都没有运行 :-( 当然也没有通知...
我所做的任何假设是否有误,还是我遗漏了什么?任何帮助将不胜感激!
谢谢!
【问题讨论】:
标签: c# silverlight user-controls inotifypropertychanged