Friday, December 31, 2010

PriorityBinding – Binding the async way

I keep discovering features in WPF/Silverlight data binding. The newest addition to my knowledge base is PriorityBinding. With PriorityBinding you can associate binding target property to a group of bindings. The binding with the highest priority is evaluated and become active binding.

Let us look at an example:

Say we want to load some data and display it. The sequence of data being fetched, loaded and displayed takes sometime. During this period we want the user to see appropriate messages.

image

image

image 

This is how xaml will look:

<TextBlock Width="200"
           HorizontalAlignment="Center"
           VerticalAlignment="Center"
           TextAlignment="Center"
           FontSize="15"
           Background="Azure"
           Foreground="Blue">
    <TextBlock.Text>
        <PriorityBinding>
            <Binding Path="Loaded"
                     IsAsync="True" />
            <Binding Path="LoadingData"
                     IsAsync="True" />
            <Binding Path="FetchingData" />
        </PriorityBinding>
    </TextBlock.Text>
</TextBlock>

Note that we have specified IsAsync="True" for 1st and 2nd binding which means that these two operations will run on a separate thread. The priority of bindings is defined by the order in which they appear. The first binding will have highest priority and the last binding will have lowest priority.

and this is the viewmodel:

public class DataVM
    {
        public string FetchingData
        {
            get
            {
                return "Fetching Data...";
            }
        }

        public string LoadingData
        {
            get
            {
                Thread.Sleep(5000);
                return "Loading Data...";
            }
        }

        public string Loaded
        {
            get
            {
                Thread.Sleep(10000);
                return "Data Loaded.";
            }
        }
    }

To simulate long running operations we have added Sleep to LoadingData and Loaded properties.

With PriorityBinding group defined, the evaluated property with the highest priority is set as active binding. Initially, the only property evaluated is FetchingData and hence set as active binding. After, 5 seconds LoadingData which has a higher priority gets evaluated and becomes active binding. After 10 seconds, Loaded property which has the highest property gets evaluated and becomes the active binding. According, to the active binding you can see appropriate message in the text block.

PriorityBinding only works in WPF and not in Silverlight.

Download the code here

No comments:

Post a Comment