请参阅WPF列表视图逐个添加项目而不是一次添加所有项目

时间:2014-10-30 12:25:57

标签: c# wpf

我花了很多年的时间进行实验和谷歌搜索,但到目前为止还没有得到答案

我有一个WPF列表视图,它使用WrapPanel作为其容器容器。

出于各种原因,我不想虚拟化包装面板。

是否可以在值转换器中显示已添加的项目?这样当用户加载时,用户不会看空白屏幕?

1 个答案:

答案 0 :(得分:0)

这是一种非常常见的情况,所以我很惊讶您在搜索过程中没有找到任何内容。也许如果你使用“异步”这个词,你会有更多的运气。无论哪种方式,答案都是使用Dispatcher class

简而言之,您可以将任务添加到UI Dispatcher对象的消息队列中,以便它可以异步运行它们。这里有很多这样的例子,但是我在Java2s网站的Load the Items in a ListBox Asynchronously页面找到了这个例子:

<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);
        }
    }
}
相关问题