【问题标题】:Silverlight4 + C#: Using INotifyPropertyChanged in a UserControl to notify another UserControl is not notifyingSilverlight4 + C#:在 UserControl 中使用 INotifyPropertyChanged 通知另一个 UserControl 没有通知
【发布时间】: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


    【解决方案1】:

    必须访问该属性才能使通知生效。我在代码中没有看到您将值设置为“ItemsCollection”的任何地方。

    我通常遵循这种模式:

      public ObservableCollection<ClassItem> ItemsCollection
            {
                get
                {
                    return _itemsCollection;
                }
                set
                {
                    _itemsCollection= value;
                    NotifyPropertyChanged("ItemsCollection");
                }
            }
    

    然后更新 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);
        }
    

    【讨论】:

    • 杰森死心塌地。仅仅创建一个 ClassItem 是不够的。您需要将每一个(或 DisplayItems 中的“var items”集合)添加到 Class2 对象的 ItemsCollection。
    • 好吧,我已经搞砸了几个小时的代码,但我真的无法让它工作......我真的很难创建类型“GetData()”来自杰森的代码。我没有这样的对象,我正在使用 ClassItem(提供模型)和 Class2,它应该在创建对象 ClassItem 时通知。我试图移动从对象类型 GetData 中的 XML 检索数据的部分代码,但我没有在 resultData = new GetData(); 中检索任何“ClassItems”。我确定我错过了一些愚蠢的事情......
    • 这只是一个获取数据的函数。您将在问题中使用 Linq 语句的结果。