2

我尝试在集合更改时运行一些代码。我将集合作为数据类中的属性:

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

并在这样的代码中注册它:

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

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

4

1 回答 1

2

您应该避免为集合类型设置属性访问器,原因之一是您在此处遇到的事件。另一个问题是,如果有人缓存了集合并稍后将项目添加到其中。

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

相反,删除 set-accessor 并直接使用现有集合。

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) { }
}
于 2013-06-17T12:13:06.987 回答