Friday, 28 July 2006

Just a little tip, showcasing the power of Xaml and the efficiency of good code/design separation.

When you are fetching data from a server, you could (and actually should) use the DataModel-View-ViewModel pattern, as described by Dan Crevier from the Microsoft Max team. It uses a viewmodel-class to bind your Xaml against. Dan then implements a 'state' property to indicate whether the model is finished fetching and is in a 'bindable' state.

If you are short on time, or have other reasons not to implement such a strategy, you are probably binding straight to objects that are still Null during the fetch-action.
In either case, it would be nice to let the user know that data is being fetched.

In my case, I had a lot of <TabItem>'s that are being filled with data, one-by-one, by setting the datacontext directly. While designing the user interface, I do not want to have to think about the possibility of binding against an invalid object (it being null). So I created a style, that I put in the application resources. The style replaces my content-template with a temporary template, whilst in invalid state. I was extremely satisfied with the solution, because it was so dead-easy, and it works like a charm.

Here is the code (don't mock my visually stunning border please ;-) ):

    <Style BasedOn="{StaticResource {x:Type TabItem}}" TargetType="{x:Type TabItem}">


        <Trigger Property="DataContext" Value="{x:Null}">

          <Setter Property="ContentTemplate">



                <Border CornerRadius="5" BorderThickness="2" BorderBrush="Black" Background="Yellow" Height="60" Width="280"

                        HorizontalAlignment="Center" VerticalAlignment="Center">

                  <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">Data is being fetched</TextBlock>








I was pleasantly surprised by the simplicity of the code. The DataContext is used in a trigger to set the content-template.

Comments are closed.