异步方式向WPF ListBox控件中一条一条添加记录
向ListBox绑定数据源时,如果数据量过大,可能会使得程序卡死,这是就需要一条一条的向ListBox的数据源中添加记录了,下面是个小Demo:
1.前台代码,就是一个ListBox控件
<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> <ListBox x:Name="listBox"></ListBox> </Grid> </Window>
2.后台代码,就是不断的向ListBox的绑定的数据源中添加记录,这里只是添加了一个描述数字,不断的调用委托添加数据,如果想停止添加数据时可以写停止条件。
using System.Collections.ObjectModel; using System.Windows; using System.Windows.Threading; namespace WpfApplication1 { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { private ObservableCollection<string> _numberDescriptions; public MainWindow() { InitializeComponent(); Loaded += MainWindow_Loaded; } private void MainWindow_Loaded(object sender, RoutedEventArgs e) { _numberDescriptions = new ObservableCollection<string>(); listBox.ItemsSource = _numberDescriptions; Dispatcher.BeginInvoke(DispatcherPriority.Background, new LoadNumberDelegate(LoadNumber), 1); } private void LoadNumber(int number) { _numberDescriptions.Add("Number " + number); Dispatcher.BeginInvoke(DispatcherPriority.Background, new LoadNumberDelegate(LoadNumber), ++number); } private delegate void LoadNumberDelegate(int number); } }
3.效果图