简体   繁体   中英

See WPF list view adding items 1 by one instead of all at once

I have spent ages experimenting and googling but have thus far come up with no answer

I have a WPF list view that is using a WrapPanel as its items container.

For various reasons I dont want to virtualise the wrap panel.

Is it possible to show the items being added one by as they are completed in the value converter? so that the user is not looking at a blank screen while the items are loading?

This is a very common scenario, so I'm surprised that you didn't find anything during your search. Perhaps if you would have used the word 'Asynchronous', you would have had more luck. Either way, the answer is to use the Dispatcher class .

In short, you can add tasks to the message queue of the UI Dispatcher object, so that it can run them asynchronously. There are many examples of this online, but here is one that I found in the Load the Items in a ListBox Asynchronously page of the Java2s website:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPF" Height="200" Width="300"
    Loaded="Window_Loaded">

    <Window.Resources>
        <DataTemplate x:Key="ListItemTemplate">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding}" VerticalAlignment="Center"/>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>
    <StackPanel>
        <ListBox x:Name="listBox" ItemTemplate= "{StaticResource ListItemTemplate}"/>
    </StackPanel>
</Window>

//File:Window.xaml.cs

using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Threading;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        private ObservableCollection<string> numberDescriptions;

        public Window1()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            numberDescriptions = new ObservableCollection<string>();

            listBox.ItemsSource = numberDescriptions;

            this.Dispatcher.BeginInvoke(DispatcherPriority.Background,new LoadNumberDelegate(LoadNumber), 1);
        }
        private delegate void LoadNumberDelegate(int number);

        private void LoadNumber(int number)
        {
            numberDescriptions.Add("Number " + number.ToString());
            this.Dispatcher.BeginInvoke(DispatcherPriority.Background,new LoadNumberDelegate(LoadNumber), ++number);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM