Mega Code Archive

 
Categories / C# / WPF
 

Load the Data for a Window Asynchronously After It Has Rendered

<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">     <StackPanel>         <TextBlock>One Million Numbers:</TextBlock>         <ListBox x:Name="listBox"/>     </StackPanel> </Window> //File:Window.xaml.cs using System.Windows; using System.Windows.Threading; using System.Collections.Generic; namespace WpfApplication1 {     public partial class Window1 : Window     {         public Window1()         {             InitializeComponent();         }         private void Window_Loaded(object sender, RoutedEventArgs e)         {             this.Dispatcher.BeginInvoke(DispatcherPriority.Background,new LoadNumbersDelegate(LoadNumbers));         }         private delegate void LoadNumbersDelegate();         private void LoadNumbers()         {             List<string> numberDescriptions = new List<string>();             for(int i = 1; i <= 1000000; i++)             {                 numberDescriptions.Add("Number " + i.ToString());             }             listBox.ItemsSource = numberDescriptions;         }     } }