Question

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>)?

Was it helpful?

Solution

When theObservableCollection changes, how does the ListBox know? You have to implement like you mentioned INotifyCollectionChanged and then update the ItemSource with the new enumerable data inside the event handler.

ObservableCollection is an INotifyCollectionChanged. Use casting

var collectionChanged = yourObCollection as INotifyCollectionChanged;

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

inside the handler do your own logic to update the item source

OTHER TIPS

Have you considered binding to the original collection but running it through a converter in order to pull out the LogEvents?

The converter should be able to simply return subSteps.SelectMany(s => s.LogEvents).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top