I have just seen a WPF application what was showing some list of items coming from a web service call. To avoid blocking the UI thread the viewmodel was using the threadpool to do the web request and when the response arrived it used the PropertyChanged event to notify the ui to “refresh” the binding. This all seems reasonable, but wpf has built-in support for this scenarios, namely the IsAsync property of the Binding class. Using this property is fairly simple and helps to avoid that bunch of code that one needs to write to achieve the same results. Here is a simple example, first the code behind simulating a long running task.
1: using System.Collections.Generic;
2: using System.ComponentModel;
3: using System.Threading;
4: using System.Windows;
5:
6: namespace AsyncBinding
7: {
8: public partial class MainWindow : Window
9: {
10: public MainWindow()
11: {
12: InitializeComponent();
13: this.DataContext = this;
14: }
15:
16: private List<Element> elements;
17:
18: public IEnumerable<Element> Elements
19: {
20: get
21: {
22: if (elements == null)
23: {
24: elements = new List<Element>();
25: Thread.Sleep(5000);
26: for (int i = 0; i < 10; i++)
27: {
28: elements.Add(new Element() { Value = "Value" + i });
29: }
30: }
31: return elements;
32: }
33: }
34: }
35:
36: public class Element
37: {
38: public string Value { get; set; }
39: }
40: }
41:
For this simple example the DataContext is the window itself and it has the Elements property which does take long time to read for the first time. The xaml of the window:
1: <Window x:Class="AsyncBinding.MainWindow"
2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4: Title="MainWindow" Height="350" Width="525">
5: <Grid>
6: <ListBox ItemsSource="{Binding Elements, IsAsync=True}">
7: <ListBox.ItemTemplate>
8: <DataTemplate>
9: <TextBlock Text="{Binding Value}" />
10: </DataTemplate>
11: </ListBox.ItemTemplate>
12: <ListBox.Style>
13: <Style TargetType="ListBox">
14: <Style.Triggers>
15: <Trigger Property="HasItems" Value="false">
16: <Setter Property="Template">
17: <Setter.Value>
18: <ControlTemplate>
19: <Border BorderBrush="Aqua" BorderThickness="5">
20: <TextBlock Text="Please wait.." HorizontalAlignment="Center" VerticalAlignment="Center"/>
21: </Border>
22: </ControlTemplate>
23: </Setter.Value>
24: </Setter>
25: </Trigger>
26: </Style.Triggers>
27: </Style>
28: </ListBox.Style>
29: </ListBox>
30: </Grid>
31: </Window>
32:
At line six the IsAsync property is set to true for the Binding doing the binding for the ItemsSource of the ListBox. Also from line twelve to twenty-eight there is some added style to provide some information for the user while waiting for the list items.
In my opinion this feature is really usefull in these common situations.