【问题标题】:When binding an ObservableCollection<T> to a ListView, how does the ListView go about retrieving the data to display?将 ObservableCollection<T> 绑定到 ListView 时,ListView 如何检索要显示的数据?
【发布时间】:2012-02-20 15:59:42
【问题描述】:

我在浏览 Microsoft 的网站时发现ObservableCollection<T>

我想出了一个快速的场景,并确定我实际上可以使用这样的东西。

我创建了一个继承自 ObservableCollection 的示例类,如下所示:

public class Ledger : ObservableCollection<LedgerEntry>, IEnumerable
{
    private ObservableCollection<LedgerEntry> _items;
    private decimal _currentBalance;

    public Ledger(IEnumerable<LedgerEntry> items)
        : base(items)
    {
        _items = new ObservableCollection<LedgerEntry>(items);
        _currentBalance = 0m;
    }

    public new IEnumerator GetEnumerator()
    {
        var enumerator = _items.GetEnumerator();

        while (enumerator.MoveNext())
        {
            var currentItem = enumerator.Current;

            _currentBalance += currentItem.Amount;
            currentItem.SetBalance(_currentBalance);

            yield return currentItem;
        }
    }
}

想想一个银行账户——我希望集合中包含的每个 LedgerEntry “知道”它的余额。

任何人——

我想知道的是——鉴于上面的例子,当我将它绑定到 ListView 时,我看到 GetEnumerator() 被调用一次,现在我很好奇——ListView 实际上是如何检索/查看集合中包含的数据?

我的想法是它会迭代可枚举,但显然我错了。

关于它如何工作的任何信息?

谢谢!

【问题讨论】:

    标签: c# wpf data-binding


    【解决方案1】:

    如果集合实现了IList&lt;T&gt;,它将用于通过索引访问项目。

    【讨论】:

    • 奇怪的是,如果我直接实现 IEnumerable,GetEnumerator 方法会被调用一次,但如果我从类签名中去掉“, IEnumerable”,则根本不会调用它。
    猜你喜欢
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 2012-05-26
    • 2018-05-21
    • 1970-01-01
    • 2017-09-29
    相关资源
    最近更新 更多