0

I have a class that defines a custom GetEnumerator() function(by implementing IEnumerable<>). I use it to iterate in a contiguous manner over several ObservableCollection<LogEvent> that are in every TestStep. I have a private ObservableCollection<TestStep> that contains all the needed data.

I would like to use an instance of this class as the ItemsSource of a ListBox. However, the ListBox never gets updated when the underlying data(ObservableCollection<LogEvent>) is updated. Here's a sample of that class:

public class FlatLogViewModel : IEnumerable<LogEvent>
{
    public FlatLogViewModel(ObservableCollection<TestStep> subSteps)
    {
        m_subSteps = subSteps;            
    }

    public IEnumerator<LogEvent> GetEnumerator()
    {
        foreach (TestStep step in SubSteps)
        {
            // step.LogEvents is an ObservableCollection<LogEvent>
            foreach (LogEvent logEvent in step.LogEvents)
                yield return logEvent;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }

    private ObservableCollection<TestStep> m_subSteps;
}

I'm not sure if I should/can implement INotifyCollectionChanged here. How can I know if ObservableCollection has been modified?

My question is: how can I get the ListBox to display the changes happening in LogEvents(which is of type ObservableCollection<LogEvent>)?

4

2 回答 2

1

您是否考虑过绑定到原始集合但通过转换器运行它以拉出LogEvents?

转换器应该可以简单return subSteps.SelectMany(s => s.LogEvents)

于 2014-03-25T22:42:58.080 回答
1

当 theObservableCollection 发生变化时,ListBox 是如何知道的?您必须像您提到的那样实现 INotifyCollectionChanged,然后使用事件处理程序中的新可枚举数据更新 ItemSource。

ObservableCollection is an INotifyCollectionChanged.使用铸造

var collectionChanged = yourObCollection as INotifyCollectionChanged;

 if( collectionChanged !=null)
{
   collectionChanged.CollectionChanged += YourEventHandler; 
}

在处理程序内部执行您自己的逻辑来更新项目源

于 2014-03-25T20:18:42.080 回答