You can use a System.Diagnostics.Stopwatch
for this. Make sure that you start it before you set the ListBox.ItemsSource
property and stop it as you said, in the ListBox.Loaded
event:
In XAML:
<ListBox Name="ListBox" />
In code constructor:
public MainWindow()
{
InitializeComponent();
ListBox.Loaded += new RoutedEventHandler(ListBox_Loaded);
Items.AddRange(Enumerable.Range(1, 100000000));
stopwatch = new Stopwatch();
stopwatch.Start();
ListBox.ItemsSource = Items;
}
Add the handler with a break point after the call to stop the Stopwatch
:
private void ListBox_Loaded(object sender, RoutedEventArgs e)
{
stopwatch.Stop();
TimeSpan elapsedTime = stopwatch.Elapsed;
}
However, unless you have millions of rows of data, or extremely complicated DataTemplates
, you may not see much differences. In this simple example, these 100,000,000 numbers are processed in well under one second. Even when I added a larger DataTemplate
for the integers, it still rendered them all in just over one second. Furthermore, repeatedly running this scenario will return differing results, so this is somewhat unreliable as well.