Improve performance for huge ListBox in StackPanel?

前端 未结 1 1821
挽巷
挽巷 2021-02-06 09:12

I am using a StackPanel to layout several controls vertically (ie, Title, sub titles, listbox, separator, listbox, etc).

The StackPanel is a child of a ScrollViewer to e

1条回答
  •  梦谈多话
    2021-02-06 09:54

    you may perhaps limit the maximum size of the huge list box and enable Virtualization

    eg

    
    

    this will enable the ListBox to load a few items only and will enable a scrollbar on listbox to scroll to rest of the items if needed.

    at the same time setting VirtualizationMode to Recycling will help you to reuse the complex data templates thus eliminating the need of re creating them again for every item.


    EDIT

    here is a solution based on your sample, I have used CompositeCollection with Virtualization to achieve the desired.

    xaml

    
        
            
                
                    
                    
                    

    code

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var items = new ObservableCollection();
            foreach (var i in Enumerable.Range(0, 10000).Select(i => new Permission() { Name = "Permission " + i }))
            { items.Add(i); }
            DataContext = items;
        }
    }
    
    public class Permission
    {
        public string Name { get; set; }
    }
    

    since we can not create data template for string so I changed the string collection to Permission collection. I hope in your real project it would be something similar.

    give this a try and see if this is close to what you need.

    note: you may safely ignore if there is any designer warning on Collection="{Binding DataContext, Source={x:Reference listbox}}"

    0 讨论(0)
提交回复
热议问题