这可以通过使用从您的任务调用的 Disptacher 的 BeginInvoke 方法将新元素添加到您的可观察集合中来完成。就像是:
//MainWindow.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ListView ItemsSource="{Binding MyList}" Grid.Row="0" />
<Button Content="Load" Click="OnLoadClicked" Grid.Row="1" Height="30" />
</Grid>
</Window>
//MainWindow.xaml.cs
using System;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private VM _vm = new VM();
public MainWindow()
{
InitializeComponent();
this.DataContext = _vm;
}
private void OnLoadClicked(object sender, RoutedEventArgs e)
{
Load10Rows();
}
private void Load10Rows()
{
Task.Factory.StartNew(() =>
{
for (int i = 0; i < 10; i++)
{
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
_vm.MyList.Add(DateTime.Now.ToString());
}), DispatcherPriority.Background);
// Just to simulate some work on the background
Thread.Sleep(1000);
}
});
}
}
public class VM
{
private ObservableCollection<string> _myList;
public VM()
{
_myList = new ObservableCollection<string>();
}
public ObservableCollection<string> MyList
{
get { return _myList; }
}
}
}
如果您有大量记录,您可能需要对其进行分块,否则只需为每条记录调用 Disptacher。