ObservableCollections的PropertyEventChangedHandler未触发

时间:2016-06-03 10:15:12

标签: c# events observablecollection inotifypropertychanged

我已经定义了一个Observable集合,如下所示,

public class PropertyFieldsInExcel
{
    public string LongNames { get; set; }
    public string ShortNames { get; set; }
    public string CNames { get; set; }                              
}

static ObservableCollection<PropertyFieldsInExcel> Properties = 
    new ObservableCollection<PropertyFieldsInExcel>();

我有一个方法可以改变那个类中某些元素的值,就像这样,

public static void AutofillCell()
{            
    ((INotifyPropertyChanged)Properties).PropertyChanged += 
        new PropertyChangedEventHandler(PropertyChangedEvent);            

    Properties[i].CNames = "It works";
    Properties[i].CNames = "Ha ha ha";            

    ((INotifyPropertyChanged)Properties).PropertyChanged -= 
        new PropertyChangedEventHandler(PropertyChangedEvent);
}

如上所示,当我为特定元素指定值时,事件不会触发。为什么?我犯了什么错误?

事件处理程序的代码是这样的,

private static void PropertyChangedEvent(object sender, PropertyChangedEventArgs e)
{
    //Some code to be executed
}

1 个答案:

答案 0 :(得分:1)

两个问题:

1)PropertyFieldsInExcel未实现INotifyPropertyChanged

2)ObservableCollection可以在项目更改时通知您,但仅在您手动订阅所有项目的已更改事件后才会通知您。

来自Uwe Keim的评论中的链接提供了一个优秀的例子......