PropertyChanged事件不适用于yield创建的集合

时间:2016-02-26 08:57:52

标签: c# wpf inotifypropertychanged yield

为什么不使用以下代码?

我有这堂课:

public class ExportSetting : INotifyPropertyChanged
{
    public Guid Guid { get; set; }
    public string Name { get; set; }
    private bool export;

    public bool Export
    {
        get { return export; }
        set
        {
            export = value;
            NotifyPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged([CallerMemberName]string propertyName = null)
    {
        if (!string.IsNullOrEmpty(propertyName) && PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

我使用命令yield:

创建了集合
public IEnumerable<ExportSetting> SequencesToExport
    {
        get { return sequencesToExport; }
        set { sequencesToExport = value; }
    }

...

    sequencesToExport = FillSequencesSetting(sequences);

    private IEnumerable<ExportSetting> FillSequencesSetting(List<MTFSequence> sequences)
    {
        foreach (var item in sequences)
        {
            yield return new ExportSetting(item.Id, item.Name, true);
        }
    }

当从UI更改属性Export(从类ExportSetting)时,应该引发事件PropertyChanged,但此事件为null。

(XAML中的ListBox具有与属性SequenceToExport绑定的ItemsSource)

当我像这样修改了集合的创建时,一切正常:

private IEnumerable<ExportSetting> FillSequencesSetting(List<MTFSequence> sequences)
    {
        List<ExportSetting> tmp = new List<ExportSetting>();
        foreach (var item in sequences)
        {
            tmp.Add(new ExportSetting(item.Id, item.Name, true));
        }
        return tmp;
    }

为什么命令yield导致事件PropertyChanged没有注册并且为null,当我使用通用List创建集合时,事件是否正常工作? 谢谢你的回答。

2 个答案:

答案 0 :(得分:3)

您需要实现可枚举。使用当前代码,每次枚举枚举时都会运行foreach循环,每次都会创建新的ExportSetting个对象。

修正:

sequencesToExport = FillSequencesSetting(sequences).ToArray();

或者:

sequencesToExport = FillSequencesSetting(sequences);

private IEnumerable<ExportSetting> FillSequencesSetting(List<MTFSequence> sequences)
{
    return sequences.Select(x => new ExportSetting(x.Id, x.Name, true)).ToArray();
}

答案 1 :(得分:0)

您错过了SequencesToExport属性更改时的通知:

public bool Export
{
    get { return export; }
    set
    {
        export = value;
        NotifyPropertyChanged();
        NotifyPropertyChanged(nameof(SequencesToExport));
    }
}