【问题标题】:Custom IEnumerable as ItemsSource for ListBox自定义 IEnumerable 作为 ListBox 的 ItemsSource
【发布时间】:2014-03-25 20:07:56
【问题描述】:

我有一个定义自定义 GetEnumerator() 函数的类(通过实现 IEnumerable)。我用它以连续的方式迭代每个 TestStep 中的几个ObservableCollection<LogEvent>。我有一个私人的ObservableCollection<TestStep>,其中包含所有需要的数据。

我想使用这个类的一个实例作为 ListBox 的 ItemsSource。但是,当基础数据 (ObservableCollection<LogEvent>) 更新时,ListBox 永远不会更新。这是该类的示例:

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;
}

我不确定我是否应该/可以在此处实施 INotifyCollectionChanged。如何知道 ObservableCollection 是否被修改?

我的问题是:如何让 ListBox 显示 LogEvents 中发生的变化(类型为 ObservableCollection&lt;LogEvent&gt;)?

【问题讨论】:

    标签: c# wpf listbox enumerator inotifycollectionchanged


    【解决方案1】:

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

    ObservableCollection is an INotifyCollectionChanged. 使用强制转换

    var collectionChanged = yourObCollection as INotifyCollectionChanged;
    
     if( collectionChanged !=null)
    {
       collectionChanged.CollectionChanged += YourEventHandler; 
    }
    

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

    【讨论】:

    • 是的,但是我如何检测底层 ObservableCollection 何时发生变化,以便在适当的时候触发 CollectionChanged 事件?
    【解决方案2】:

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

    转换器应该可以简单地return subSteps.SelectMany(s =&gt; s.LogEvents)

    【讨论】:

    • 我没有想到这一点,我认为它会起作用,但 Dan 的解决方案似乎正是我所需要的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 2021-04-02
    相关资源
    最近更新 更多