我不能注册ObservableCollection的事件CollectionChanged

本文关键字:事件 CollectionChanged ObservableCollection 不能 注册 | 更新日期: 2023-09-27 18:18:38

我尝试在更改集合时运行一些代码。我保持集合属性在数据类:

public static ObservableCollection<OfferedConfiguration> DeviceAdjustedConfigurations
{
     get { return deviceAdjustedConfigurations; }
     set { deviceAdjustedConfigurations = value; }
}

并将其注册到代码中,如下所示:

Data.DeviceAdjustedConfigurations.CollectionChanged += new NotifyCollectionChangedEventHandler(DeviceAdjustedConfigurationsCollectionChanged);

但注册后CollectionChangednull,委托方法中没有运行相应的代码。在这个地方DeviceAdjustedConiguration已经包含了一些数据。我做错了什么?

我不能注册ObservableCollection的事件CollectionChanged

应该避免使用集合类型的set属性访问器,原因之一就是您在这里遇到的事件。另一个问题是,如果有人缓存集合并稍后向其中添加项目。

var old = obj.DeviceAdjustedConfigurations;
obj.DeviceAdjustedConfigurations = new ObservableCollection<OfferedConfiguration>();
old.Add(new OfferedConfiguration()); // what should happen here?

应该删除set访问器,直接使用现有的集合。

obj.DeviceAdjustedConfigurations.Add(new OfferedConfiguration());

如果您真的需要设置集合,您需要处理这个问题,例如,从拥有DeviceAdjustedConfigurations的类的属性更改事件。

public class Item
{
    public static ObservableCollection<OfferedConfiguration> DeviceAdjustedConfigurations
    {
        get { return deviceAdjustedConfigurations; }
        set
        {
            if (deviceAdjustedConfigurations != value)
            {
                onDeviceConfigurationsChanging(deviceAdjustedConfigurations, value);
                deviceAdjustedConfigurations = value;
            }
        }
    }
    public static event EventHandler<ConfigurationChangedEventArgs> DeviceConfigurationsChanging;
    private static void onDeviceConfigurationsChanging(
        ObservableCollection<OfferedConfiguration> oldList,
        ObservableCollection<OfferedConfiguration> newList)
    {
        var handler = DeviceConfigurationsChanging;
        if (handler != null)
        {
            handler(null, new ConfigurationChangedEventArgs(oldList, newList));
        }
    }
}
public class ConfigurationChangedEventArgs : EventArgs
{
    public ConfigurationChangedEventArgs(
        ObservableCollection<OfferedConfiguration> oldList,
        ObservableCollection<OfferedConfiguration> newList)
    {
        OldList = oldList;
        NewList = newList;
    }
    public ObservableCollection<OfferedConfiguration> OldList { get; private set; }
    public ObservableCollection<OfferedConfiguration> NewList { get; private set; }
}
public class Consumer
{
    public void foo()
    {
        Item.DeviceConfigurationsChanging += updateEvents;
    }
    private void updateEvents(object sender, ConfigurationChangedEventArgs args)
    {
        args.OldList.CollectionChanged -= onCollectionChanged;
        args.NewList.CollectionChanged += onCollectionChanged;
    }
    private void onCollectionChanged(object sender, NotifyCollectionChangedEventArgs args) { }
}