1

Реализован биндинг ListView к Collection в результате в логах вижу что запрос к модели по индексу повторяется по два раза для каждого элемента выводимого на экран, что резко понижает быстродействие, если items-ы генерируются на-лету.

Лог:

I0 I0 I1 I1 I2 I2...

XAML

<Grid>
    <ListView Name="bindingListView" ItemsSource="{Binding SampleData}">
        <ListView.View>
            <GridView>
                <GridViewColumn Width="140" Header="First Name"
                                DisplayMemberBinding="{Binding Name}"  />
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;

namespace WpfApplication1
{
    public class TCollection<TT> : IList<TT>, ICollection<TT>, 
IList, ICollection, IReadOnlyList<TT>, IReadOnlyCollection<TT>, 
IEnumerable<TT>, IEnumerable
   {
        public Collection<TT> upList;
        public object SyncRoot { get { return this; } }
        public bool IsReadOnly { get { return true; } }
        public bool IsSynchronized { get { return false; } }
        public bool IsFixedSize { get { return true; } }
        public TCollection() { upList = new Collection<TT>(); }
        public TCollection(IList<TT> list) { 
             upList = new Collection<TT>(list); }
        public int Count { get { return upList.Count(); } }
        object IList.this[int index] {
            get {
                Console.WriteLine("I{0}", index);
                return upList[index];
            }
            set { upList[index] = (TT)value; } }
        public TT this[int index] { get { return upList[index]; } 
                                    set { upList[index] = value; } }
        int IList.Add(object value) { this.Add((TT)value); return 1; }
        public void Add(TT item) { upList.Add(item); }
        public void Clear() { upList.Clear(); }
        bool IList.Contains(object obj) { 
            return this.Contains((TT)obj); }
        public bool Contains(TT item) { return upList.Contains(item); }
        public void CopyTo(TT[] array, int index) { 
           upList.CopyTo(array, index); }
        public void CopyTo(System.Array array, int index) {
            upList.CopyTo((TT[])array, index); }
        public IEnumerator<TT> GetEnumerator() { 
            return upList.GetEnumerator(); }
        IEnumerator IEnumerable.GetEnumerator() { 
            return this.GetEnumerator(); }
        public int IndexOf(TT item) { return upList.IndexOf(item); }
        public int IndexOf(object item) { 
            return this.IndexOf((TT)item); }
        public void Insert(int index, TT item) { 
            upList.Insert(index, item); }
        public void Insert(int index, object item) { 
            this.Insert( index, (TT)item ); }
        public bool Remove(TT item) { return upList.Remove( item ); }
        public void Remove(object item) { upList.Remove((TT)item); }
        public void RemoveAt(int index) { upList.RemoveAt(index); }
    }
    public class People
    {
        string _name;
        public People(string name) { _name = name; }
        public string Name { get { return _name; } set { _name = value; } }
    }
    public partial class MainWindow : Window
    {
        TCollection<People> upList;
        public MainWindow()
        {
            upList = new TCollection<People>();
            for (int i = 0; i < 1000000; ++i) {
                upList.Add(new People(i.ToString()));
            }
            DataContext = this;
            InitializeComponent();
        }
        public TCollection<People> SampleData { get { return upList; } }
    }
}
6
  • Если вы пользуетесь MVVM, то должны знать, что привязываться к модели нельзя. Исправьте это, проблема уйдёт.
    – VladD
    15 июл 2017 в 19:36
  • Спасибо за ответ, но такого поведения от вьюшки не ожидал: три раза перечитывает страницу при старте (каждый компонент дважды), при ресайзе перечитывает из модели все компоненты - это как-то не правильно. А если дать только IEnumerable, то считает все итемсы.
    – Alexander
    15 июл 2017 в 19:54
  • @VladD что вы имеете ввиду?
    – user227049
    15 июл 2017 в 20:02
  • с какой целью разработчики ListView делали эти повторные вызовы получения значения по индексу
    – Alexander
    15 июл 2017 в 20:15
  • @FoggyFinder: VM обычно выставляет не IEnumerable, а ObservableCollection. Раз у ТС выставлен генератор, то он, очевидно, привязывает View прямо к модельному объекту.
    – VladD
    15 июл 2017 в 20:43

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Посмотрите другие вопросы с метками или задайте свой вопрос.