Colin Eberhardt's Adventures in WPF

Linq to Visual Tree

March 4th, 2010

This blog post demonstrates a Linq API which can be used to query the WPF / Silverlight Visual Tree. You can find a few other Linq to Visual Tree techniques on other blogs, but what makes this one unique is that it retains, and allows queries that make use of the tree like structure rather than simply flattening it.

I have recently published an article on codeproject which describes a technique for generating Linq API for querying tree-like structures. This blog post makes use of a generated API for WPF / Silverlight. If you are interested in the more generic approach, and how this API was constructed, (and how it is influenced by XPath) head on over to codeproject …

What I will provide here is a brief overview of the Linq to Visual Tree API. The full sourcecode for this API is at the end of this article.

The Linq to Visual Tree API defines a number of extension methods on DependencyObject that provide mechanisms for navigating to other DependencyObject instances. I will provide a few examples that query the following simple markup:

<Grid x:Name="GridOne" Background="White">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
 
    <TextBox x:Name="TextBoxOne" Text="One" Grid.Row="0" />
 
    <StackPanel x:Name="StackPanelOne" Grid.Row="1">
        <TextBox x:Name="TextBoxTwo" Text="Two" />
 
        <Grid x:Name="GridTwo">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
 
            <TextBox x:Name="TextBoxThree" Text="Three" Grid.Row="0" />
 
            <StackPanel x:Name="StackPanelTwo" Grid.Row="1">
                <TextBox x:Name="TextBoxFour" Text="Four"/>                    
            </StackPanel>
        </Grid>
    </StackPanel>
</Grid>

We’ll start with a simple example. Include the Linq to Visual Tree namespace, then use the Descendants method to obtain all the descendants (i.e. children and children’s children, etc …) of an object within the
visual tree.

Descendants

using LinqToVisualTree;
 
// all items within the visual tree
IEnumerable<DependencyObject> allDescendants = this.Descendants();
/*
gives ...
0 {Grid} 	[GridOne]
1 {TextBox} 	[TextBoxOne]
2 {StackPanel} 	[StackPanelOne]
3 {TextBox} 	[TextBoxTwo]
4 {Grid} 	[GridTwo]
5 {TextBox} 	[TextBoxThree]
6 {StackPanel} 	[StackPanelTwo]
7 {TextBox} 	[TextBoxFour]
*/
 
// all items within the visual tree of 'GridTwo'
var descendantsOfGridTwo = GridTwo.Descendants();
/*
gives ...
0 {TextBox} 	[TextBoxThree]
1 {StackPanel} 	[StackPanelTwo]
2 {TextBox} 	[TextBoxFour]
*/

Each of the extension methods also has a corresponding method with a generic type parameter that filters the collection to find elements of a specific type:

// all items within the visual tree of 'GridTwo' that are textboxes
var textBoxDescendantsOfGridTwo = GridTwo.Descendants()
                                         .Where(i => i is TextBox);
/*
0 {TextBox} 	[TextBoxThree]
1 {TextBox} 	[TextBoxFour]
*/
 
// a shorthand using the generic version of Descendants
var textBoxDescendantsOfGridTwo2 = GridTwo.Descendants<TextBox>();
/*
0 {TextBox} 	[TextBoxThree]
1 {TextBox} 	[TextBoxFour]
*/

Elements

The elements extension method obtains all the direct children of an item in the visual tree:

// find all direct children of this user control 
var userControlChildren = this.Elements();
/*
0 {Grid} 	[GridOne]
*/
 
// find all direct children of the grid 'GridTwo'
var gridChildren = GridTwo.Elements();
/*
0 {TextBox} 	[TextBoxThree]
1 {StackPanel} 	[StackPanelTwo]
*/
 
// find all direct children of the grid 'GridTwo' that are StackPanels
var gridChildren2 = GridTwo.Elements<StackPanel>();
/*
0 {StackPanel} 	[StackPanelTwo]
*/

There are also, ElementsBeforeSelf and ElementsAfterSelf methods that return the elements before and after the item which the method is being invoked upon.

Ancestors

The ancestors methods traverse the tree towards the root, finding all the ancestors:

// the ancestors for 'TextBoxFour'
var ancestors = TextBoxFour.Ancestors();
/*
0 {StackPanel} 	[StackPanelTwo]
1 {Grid} 	[GridTwo]
2 {StackPanel} 	[StackPanelOne]
3 {Grid} 	[GridOne]
4 {MainPage} 	[]
*/
 
// the ancestors for 'TextBoxFour' that are StackPanels
var stackPanelAncestors = TextBoxFour.Ancestors<StackPanel>();
/*
0 {StackPanel} 	[StackPanelTwo]
1 {StackPanel} 	[StackPanelOne]
*/

Putting it all together

The Linq to Tree API not only defines extension methods on DependencyObject, but also the same extension methods on IEnumerable<DependencyObject>. Unless you have previous experience of Linq to XML, I would strongly suggest reading my codeproject article to understand how this works!

This allows you to form much more complex queries. For example, you can find all TextBoxs that have a Grid as a direct parent:

var itemsFluent = this.Descendants<TextBox>()
                      .Where(i => i.Ancestors().FirstOrDefault() is Grid);
 
var itemsQuery = from v in this.Descendants<TextBox>()
                 where v.Ancestors().FirstOrDefault() is Grid
                 select v;
/*
0 {TextBox} 	[TextBoxOne]
1 {TextBox} 	[TextBoxThree]
*/

Here, you can also see we are mixing the fluent and query syntax for Linq. Both give the same result.

The next example finds all StackPanels that are within another StackPanels visual tree:

var items2Fluent = this.Descendants<StackPanel>()
                              .Descendants<StackPanel>();
 
var items2Query = from i in
                      (from v in this.Descendants<StackPanel>()
                       select v).Descendants<StackPanel>()
                  select i;
/*
0 {StackPanel} 	[StackPanelTwo]
*/

Finally, this one-liner, outputs the entire visual tree in ASCII! It makes use of the DescendantsAndSelf, Ancestors and ElementsBeforeSelf methods, plus the funky Linq Aggregate method.

string tree = this.DescendantsAndSelf().Aggregate("",
    (bc, n) => bc + n.Ancestors().Aggregate("", (ac, m) => (m.ElementsAfterSelf().Any() ? "| " : "  ") + ac,
    ac => ac + (n.ElementsAfterSelf().Any() ? "+-" : "\\-")) + n.GetType().Name + "\n");
\-MainPage
  \-Grid
    +-TextBox
    | \-Grid
    |   +-Border
    |   | \-Grid
    |   |   +-Border
    |   |   \-Border
    |   |     \-ScrollViewer
    |   |       \-Border
    |   |         \-Grid
    |   |           +-ScrollContentPresenter
    |   |           | \-TextBoxView
    |   |           +-Rectangle
    |   |           +-ScrollBar
    |   |           \-ScrollBar
    |   +-Border
    |   +-Border
    |   \-Border
    |     \-Grid
    |       +-Path
    |       \-Path
    \-StackPanel
      +-TextBox
      | \-Grid
      |   +-Border
      |   | \-Grid
      |   |   +-Border
      |   |   \-Border
      |   |     \-ScrollViewer
      |   |       \-Border
      |   |         \-Grid
      |   |           +-ScrollContentPresenter
      |   |           | \-TextBoxView
      |   |           +-Rectangle
      |   |           +-ScrollBar
      |   |           \-ScrollBar
      |   +-Border
      |   +-Border
      |   \-Border
      |     \-Grid
      |       +-Path
      |       \-Path
      \-Grid
        +-TextBox
        | \-Grid
        |   +-Border
        |   | \-Grid
        |   |   +-Border
        |   |   \-Border
        |   |     \-ScrollViewer
        |   |       \-Border
        |   |         \-Grid
        |   |           +-ScrollContentPresenter
        |   |           | \-TextBoxView
        |   |           +-Rectangle
        |   |           +-ScrollBar
        |   |           \-ScrollBar
        |   +-Border
        |   +-Border
        |   \-Border
        |     \-Grid
        |       +-Path
        |       \-Path
        \-StackPanel
          \-TextBox
            \-Grid
              +-Border
              | \-Grid
              |   +-Border
              |   \-Border
              |     \-ScrollViewer
              |       \-Border
              |         \-Grid
              |           +-ScrollContentPresenter
              |           | \-TextBoxView
              |           +-Rectangle
              |           +-ScrollBar
              |           \-ScrollBar
              +-Border
              +-Border
              \-Border
                \-Grid
                  +-Path
                  \-Path

Note: this was invoked after the LayoutUpdated event so that we not only see the elements from our XAML, but also the elements created from their templates, giving us our full run-time visual tree.

You can download a simple Silverlight application that demonstrated all the examples given above:
LinqToTree.zip.

Or, if you just want the Linq to VisualTree code, you can copy-n-paste from the windows below which has the entire API, which includes the methods illustrated above,, plus their IEnumerable equivalents, and a few others I have not illustrated.

using System;
using System.Linq;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;

namespace LinqToVisualTree
{
    /// 
    /// Adapts a DependencyObject to provide methods required for generate
    /// a Linq To Tree API
    /// 
    public class VisualTreeAdapter : ILinqTree
    {
        private DependencyObject _item;

        public VisualTreeAdapter(DependencyObject item)
        {
            _item = item;
        }

        public IEnumerable Children()
        {
            int childrenCount = VisualTreeHelper.GetChildrenCount(_item);
            for (int i = 0; i < childrenCount; i++)
            {
                yield return VisualTreeHelper.GetChild(_item, i);
            }
        }

        public DependencyObject Parent
        {
            get
            {
                return VisualTreeHelper.GetParent(_item);
            }
        }
    }
}

namespace LinqToVisualTree
{
    /// 
    /// Defines an interface that must be implemented to generate the LinqToTree methods
    /// 
    /// 
    public interface ILinqTree
    {
        IEnumerable Children();

        T Parent { get; }
    }

    public static class TreeExtensions
    {
        /// 
        /// Returns a collection of descendant elements.
        /// 
        public static IEnumerable Descendants(this DependencyObject item)
        {
            ILinqTree adapter = new VisualTreeAdapter(item);
            foreach (var child in adapter.Children())
            {
                yield return child;

                foreach (var grandChild in child.Descendants())
                {
                    yield return grandChild;
                }
            }
        }

        /// 
        /// Returns a collection containing this element and all descendant elements.
        /// 
        public static IEnumerable DescendantsAndSelf(this DependencyObject item)
        {
            yield return item;

            foreach (var child in item.Descendants())
            {
                yield return child;
            }
        }

        /// 
        /// Returns a collection of ancestor elements.
        /// 
        public static IEnumerable Ancestors(this DependencyObject item)
        {
            ILinqTree adapter = new VisualTreeAdapter(item);

            var parent = adapter.Parent;
            while (parent != null)
            {
                yield return parent;
                adapter = new VisualTreeAdapter(parent);
                parent = adapter.Parent;
            }
        }

        /// 
        /// Returns a collection containing this element and all ancestor elements.
        /// 
        public static IEnumerable AncestorsAndSelf(this DependencyObject item)
        {
            yield return item;

            foreach (var ancestor in item.Ancestors())
            {
                yield return ancestor;
            }
        }

        /// 
        /// Returns a collection of child elements.
        /// 
        public static IEnumerable Elements(this DependencyObject item)
        {
            ILinqTree adapter = new VisualTreeAdapter(item);
            foreach (var child in adapter.Children())
            {
                yield return child;
            }
        }

        /// 
        /// Returns a collection of the sibling elements before this node, in document order.
        /// 
        public static IEnumerable ElementsBeforeSelf(this DependencyObject item)
        {
            if (item.Ancestors().FirstOrDefault() == null)
                yield break;
            foreach (var child in item.Ancestors().First().Elements())
            {
                if (child.Equals(item))
                    break;
                yield return child;
            }
        }

        /// 
        /// Returns a collection of the after elements after this node, in document order.
        /// 
        public static IEnumerable ElementsAfterSelf(this DependencyObject item)
        {
            if (item.Ancestors().FirstOrDefault() == null)
                yield break;
            bool afterSelf = false;
            foreach (var child in item.Ancestors().First().Elements())
            {
                if (afterSelf)
                    yield return child;

                if (child.Equals(item))
                    afterSelf = true;
            }
        }

        /// 
        /// Returns a collection containing this element and all child elements.
        /// 
        public static IEnumerable ElementsAndSelf(this DependencyObject item)
        {
            yield return item;

            foreach (var child in item.Elements())
            {
                yield return child;
            }
        }

        /// 
        /// Returns a collection of descendant elements which match the given type.
        /// 
        public static IEnumerable Descendants(this DependencyObject item)
        {
            return item.Descendants().Where(i => i is T).Cast();
        }

        /// 
        /// Returns a collection of the sibling elements before this node, in document order
        /// which match the given type.
        /// 
        public static IEnumerable ElementsBeforeSelf(this DependencyObject item)
        {
            return item.ElementsBeforeSelf().Where(i => i is T).Cast();
        }

        /// 
        /// Returns a collection of the after elements after this node, in document order
        /// which match the given type.
        /// 
        public static IEnumerable ElementsAfterSelf(this DependencyObject item)
        {
            return item.ElementsAfterSelf().Where(i => i is T).Cast();
        }

        /// 
        /// Returns a collection containing this element and all descendant elements
        /// which match the given type.
        /// 
        public static IEnumerable DescendantsAndSelf(this DependencyObject item)
        {
            return item.DescendantsAndSelf().Where(i => i is T).Cast();
        }

        /// 
        /// Returns a collection of ancestor elements which match the given type.
        /// 
        public static IEnumerable Ancestors(this DependencyObject item)
        {
            return item.Ancestors().Where(i => i is T).Cast();
        }

        /// 
        /// Returns a collection containing this element and all ancestor elements
        /// which match the given type.
        /// 
        public static IEnumerable AncestorsAndSelf(this DependencyObject item)
        {
            return item.AncestorsAndSelf().Where(i => i is T).Cast();
        }

        /// 
        /// Returns a collection of child elements which match the given type.
        /// 
        public static IEnumerable Elements(this DependencyObject item)
        {
            return item.Elements().Where(i => i is T).Cast();
        }

        /// 
        /// Returns a collection containing this element and all child elements.
        /// which match the given type.
        /// 
        public static IEnumerable ElementsAndSelf(this DependencyObject item)
        {
            return item.ElementsAndSelf().Where(i => i is T).Cast();
        }

    }

    public static class EnumerableTreeExtensions
    {
        /// 
        /// Applies the given function to each of the items in the supplied
        /// IEnumerable.
        /// 
        private static IEnumerable DrillDown(this IEnumerable items,
            Func> function)
        {
            foreach (var item in items)
            {
                foreach (var itemChild in function(item))
                {
                    yield return itemChild;
                }
            }
        }

        /// 
        /// Applies the given function to each of the items in the supplied
        /// IEnumerable, which match the given type.
        /// 
        public static IEnumerable DrillDown(this IEnumerable items,
            Func> function)
            where T : DependencyObject
        {
            foreach (var item in items)
            {
                foreach (var itemChild in function(item))
                {
                    if (itemChild is T)
                    {
                        yield return (T)itemChild;
                    }
                }
            }
        }

        /// 
        /// Returns a collection of descendant elements.
        /// 
        public static IEnumerable Descendants(this IEnumerable items)
        {
            return items.DrillDown(i => i.Descendants());
        }

        /// 
        /// Returns a collection containing this element and all descendant elements.
        /// 
        public static IEnumerable DescendantsAndSelf(this IEnumerable items)
        {
            return items.DrillDown(i => i.DescendantsAndSelf());
        }

        /// 
        /// Returns a collection of ancestor elements.
        /// 
        public static IEnumerable Ancestors(this IEnumerable items)
        {
            return items.DrillDown(i => i.Ancestors());
        }

        /// 
        /// Returns a collection containing this element and all ancestor elements.
        /// 
        public static IEnumerable AncestorsAndSelf(this IEnumerable items)
        {
            return items.DrillDown(i => i.AncestorsAndSelf());
        }

        /// 
        /// Returns a collection of child elements.
        /// 
        public static IEnumerable Elements(this IEnumerable items)
        {
            return items.DrillDown(i => i.Elements());
        }

        /// 
        /// Returns a collection containing this element and all child elements.
        /// 
        public static IEnumerable ElementsAndSelf(this IEnumerable items)
        {
            return items.DrillDown(i => i.ElementsAndSelf());
        }

        /// 
        /// Returns a collection of descendant elements which match the given type.
        /// 
        public static IEnumerable Descendants(this IEnumerable items)
            where T : DependencyObject
        {
            return items.DrillDown(i => i.Descendants());
        }

        /// 
        /// Returns a collection containing this element and all descendant elements.
        /// which match the given type.
        /// 
        public static IEnumerable DescendantsAndSelf(this IEnumerable items)
            where T : DependencyObject
        {
            return items.DrillDown(i => i.DescendantsAndSelf());
        }

        /// 
        /// Returns a collection of ancestor elements which match the given type.
        /// 
        public static IEnumerable Ancestors(this IEnumerable items)
            where T : DependencyObject
        {
            return items.DrillDown(i => i.Ancestors());
        }

        /// 
        /// Returns a collection containing this element and all ancestor elements.
        /// which match the given type.
        /// 
        public static IEnumerable AncestorsAndSelf(this IEnumerable items)
            where T : DependencyObject
        {
            return items.DrillDown(i => i.AncestorsAndSelf());
        }

        /// 
        /// Returns a collection of child elements which match the given type.
        /// 
        public static IEnumerable Elements(this IEnumerable items)
            where T : DependencyObject
        {
            return items.DrillDown(i => i.Elements());
        }

        /// 
        /// Returns a collection containing this element and all child elements.
        /// which match the given type.
        /// 
        public static IEnumerable ElementsAndSelf(this IEnumerable items)
            where T : DependencyObject
        {
            return items.DrillDown(i => i.ElementsAndSelf());
        }
    }
}

Regards, Colin E.

My Mix10k entry – Old Skool demo – plus a few tips

January 7th, 2010

This blog post is about my entry to the Mix10k code competition, and old-skool demo, plus a few tips about how to keep you code size to below 10k.

The mix10k challenge, where you are given 10k to create a Silverlight / HTML5 application, has been on my mind for a while … the Christmas vacation was the perfect excuse to put together my entry. Inspired by the demo’s of the Amiga era, here is my mix10k old-skool demo entry:

You can view my entry (and more importantly vote for it!) at the mix10k gallery.

For me the greatest challenge was the music, not least for the fact that I am no good at writing the stuff myself! The mix10k rules are fairly relaxed, you can download content, such as images and music, allowing you to circumnavigate the 10k limit. However, I thought it would be a more interesting challenge to pack everything into 10k.

Size-limited demos typically use synthesis rather than sampling for the musics. Unfortunately Silverlight isn’t really geared towards sound synthesis, however, a few people have managed to create synthesized media sources. I decided to go the sampling route and use an MP3 track for my music, the idea being to use a short, highly compressed MP3 track and loop it. I posted a message on the 8bitcollective forums and within a day had a funky, and highly compressed, 4 second MP3 clip for my demo. The MP3 filesize of 4,248 bytes left me 5,992 to play with.

However, the next challenge was looping the audio, which is unfortunately something that is not supported out-of-the-box. For longer media clips it is acceptable to catch the MediaEnded event, re-wind and re-start. However, there is a delay of about half a second, which with a 4 second looped audio clip is pretty disruptive! Fortunately Silverlight does expose a lower level API for media via the abstract class MediaStreamSource, which has virtual methods which you can override to supply audio direct from a stream. The codeplex project ManagedMediaHelpers is a great place to start for information on how to load MP3 audio from a file. Typically the code to read and stream an MP3 file is over 10k, however, I was able to trim this down to roughly 1k by removing all the code for parsing the MP3 headers, replacing it with the hard-coded values for my specific MP3 file.

Unfortunately, when the audio was looped, it just didn’t sound right. The trouble is, within MP3 files, the audio is split into frames. Using a useful utility from codeproject, I found that my MP3 file consisted of 56 frames of ~67ms in length. However, the audio loop was not a multiple of 67ms. To rectify this, I downloaded a copy of the free audio editor Audacity, and ’stretched’ the track to fit into an integer number of frames, and re-encoded in MP3 format via lame. Finally, I had looping MP3 audio! (and 4,958 bytes left)

audacity

After the battle I had with the audio, constructing the visuals, the scrolling text, interference patterns, plasma and starfield was a piece of cake!

Here are a few quick tips for keeping your filesize under 10k.

  • Use the var keyword wherever possible
     
  • Use the using for aliasing frequently used types

    For example:

    using K = System.Windows.Media.MediaSourceAttributesKeys;
    using J= System.Windows.Media.MediaStreamAttributeKeys;
    using M = System.Math;

    With type names as long as MediaSourceAttributesKeys, you only need to use them three times for a using alias to make sense!

  • chain initialisation of variables

    The following code:

    int x1 = sin1(8) + 200
    int y1 = sin1(3) * 10 + 100
    int g = (tx - x1) * (tx - x1);

    Can be shortened to:

    int x1 = sin1(8) + 200, y1 = sin1(3) * 10 + 100, g = (tx - x1) * (tx - x1);
  • Tabs not spaces

    If you are not to bothered about squeezing the most out of those 10k bytes and want your code to look pretty, at least save yourself a bit of room by using Tabs!

  • Choose wisely between XAML and C#

    One big advantage that XAML has over C# is its use of value converters, compare the following XAML:

    <Ellipse Fill="White"/>

    to its equivalent in C#:

    var el = new Ellipse()
    {
       Fill = new SolidColorBrush(Color.FromArgb(255,255,255,255))
    };

    In this case, XAML is a clear winner.

  • Use lambda expressions for event handlers

    You can achieve great savings by including your event handling logic within anonymous delegates (via lambda expressions), it also means that you can move variables from class scope (i.e. files) to method scope and use the var keyword. Compare:

    WriteableBitmap bitmap = new WriteableBitmap(200,200);
     
    MyPage()
    {
    	var t = new DispatcherTimer();
    	t.Tick +=new EventHandler(t_Tick);
    }
     
    void  t_Tick(object sender, EventArgs e)
    {
    	// do stuff with the bitmap
    	bitmap.Invalidate();
    }

    to:

    MyPage()
    {
    	var bitmap = new WriteableBitmap(200,200);
    	var t = new DispatcherTimer();
    	t.Tick += (s,e) =>
    		{
    			// do stuff with the bitmap
    			bitmap.Invalidate();
    		};
    }
  • Ditch that App!

    The App.xaml and App.xaml.cs full of template code that you do not need. Simply ditch these files entirely and replace with a minimal application that indicates the page to display:

    public class A : Application
    {
        public A()
        {
            Startup += (i, j) => RootVisual = new MainPage();
        }
    }
  • Minify your code

    Perhaps the greatest savings can be achieved by ‘minifying’ your code, i.e. removing any extra whitespace and reducing variable, method, types names to single characters. The problem is that in doing so, your code will become unreadable!

    In order to minify my code yet maintain readability I created a very simple console application that read my application source and performed a bunch of string replacements in order to reduce its size …

    static Dictionary<string, string> reps = new Dictionary<string, string>()
    {
      {System.Environment.NewLine, ""}, 
      {"  ", " "},
      {" = ", "="},
      {" == ", "=="},
      {" * ", "*"},
      {" > ", ">"},
      {" < ", "<"},
      ...
     
      // methods 
      {"Timer_Tick", "T"},
      {"CreateLine", "g"},
      {"DrawLines", "ln"},
      ...
     
      // xaml
      {"grid", "q"},
      {"image", "o"},
      {"canvas", "c"},
      {"MainPage", "Y"},
      ...
    };

    The output of this console application is sent to another project which builds my final entry. The result of this was to make my reasonably compact code 47% smaller!

You can download my thoroughly messy and unreadable code: mix10ksrc.zip

And vote for it on the mix10k site (Did I say that already?)

Regards, Colin E.

Silverlight 4 beta released leaving Flex behind

November 19th, 2009

This post looks at the speed of development of the two leading RIA frameworks, Silverlight and Flex, giving unequivocal proof that Silverlight is better than Flex … !

This week at Microsoft’s Professional Developers Conference (PDC), there have been two big news stories. The first is the give-away of a free tablet PC to all attendees, and the second is the release of Silverlight 4 beta. Whilst the first story is sure to grab the headlines, the second is far more significant, with official launch of Silverlight 3 having passed just 4 months ago.

There are many new features in Silverlight 4 including, printing support, improved databinding, new controls, improved mouse support, clipboard, drag’n'drop, and much much more. You can be sure that Silverlight 4 will receive a lot of blog coverage over the next few months, it is worth subscribing to Silverlight Cream to get a good overview of all blogging activity. (It looks like Shawn Wildermuth is not sleeping and has blogged about the improved SL4 databinding support already!)

While the new features are very exciting, what interests me more is just how fast Silverlight is developing. Time for a bit of analysis …

Four months ago I took a detailed look at Silverlight adoptions figures, which I don’t expect to have changed much since then. This time I want to look at the rate of development of the framework itself. The following chart plots the date at which major releases of some key RIA technologies were released (plus predicted release dates for SL4 and Flex4):

progression

(Data collected from Wikipedia pages on Flash, Flex, JavaFX and Silverlight).

As you can see from the above chart Silverlight is being developed very aggressively with major versions being released with less than a year between them. Interestingly the above chart shows an almost constant development velocity for each RIA technology. Which leads me to the next chart …


velocity

Here we can see that Silverlight development is occurring at a rate of 1.5 version increments per annum (VIPA [1]) , whilst Flex is lagging behind at 0.7 VIPAs … and JavaFX just 0.3 VIPAs!

There you have it. Unequivocal proof that Silverlight is better than Flex.

Regards, Colin E.

[1] Hey look … I’ve developed a new unit here. Do you think in years to come they might come to be known as Colins? Eberhardts?

The mini-ViewModel pattern

August 7th, 2009

The construction of a ViewModel is often seen as the standard technique for solving binding problems within WPF and Silverlight. However, the addition of a ViewModel adds complexity to your code. This post describes an alternative method where a mini-ViewModel is applied directly to the problem areas in the view, leaving the rest to use simpler, straightforward binding to business objects.

One of the features of WPF / Silverlight that appealed to me immediately when I started to learn it was the flexibility of the binding framework. The concepts of DataContext inheritence and flexibility of the value converters results in a lot less glue-code, which makes me a happy developer! However, it does not take long before you start finding examples that just dont fit with the framework and things start to get just little more complex. This blog post describes one such example.

The example used in this blog post is of a very simple application which displays a business card. The business object rendered by the application, ContactDetails, has a number of simple CLR properties. Constructing a UI for viewing this business object is very easy, simply create an instance of this object (in a real application this object might come from a database or web service) and set it as the DataContext of the view:

public Page()
{
    InitializeComponent();
 
    ContactDetails details = new ContactDetails()
    {
        Company = "Scott Logic Ltd.",
        Email = "ceberhardt@scottlogic.co.uk",
        URL = "http://www.scottlogic.co.uk",
        Country = "UK",
        FullName = "Colin Eberhardt",
        PhoneNumber = 4408452241930
    };
 
    this.DataContext = details;
}

We then create some simple XAML with UI elements that bind to the various propeties of our object …

<Grid x:Name="LayoutRoot" Background="White">
    <Border BorderBrush="LightGray" Background="White"  BorderThickness="1.5" CornerRadius="20"
        VerticalAlignment="Center" HorizontalAlignment="Center">
        <Border Margin="5" BorderBrush="LightGray" BorderThickness="1.5" CornerRadius="15">
            <Border.Background>
                <ImageBrush>
                    <ImageBrush.ImageSource>
                        <BitmapImage UriSource="back.jpg" />
                    </ImageBrush.ImageSource>
                </ImageBrush>
            </Border.Background>
 
            <StackPanel Orientation="Vertical" Margin="10">
                <TextBlock Text="{Binding FullName}"
                           FontSize="15"
                           FontWeight="Bold" />
                <Rectangle Stroke="DarkGray" HorizontalAlignment="Stretch"
                           StrokeThickness="0.5" Height="1"/>
                <TextBlock Text="{Binding Company}" Margin="0,10,0,0"/>
                <StackPanel Orientation="Horizontal" >
                    <TextBlock Text="e: "/>
                    <TextBlock Text="{Binding Email}" />
                </StackPanel>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="w: "/>
                    <HyperlinkButton Content="{Binding URL}"/>
                </StackPanel>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="p: "/>
                    <TextBlock Text="{Binding PhoneNumber}"/>
                </StackPanel>
            </StackPanel>
        </Border>
    </Border>
</Grid>

And we get a lovely looking business card:

card

One problem with the above example is the phone number, outputting the raw number ‘4408452241930′ is not terribly readable, besides phone numbers have a standard format, in this case, the phone number would be represented as ‘+44 (0)845 2241930′. Also, let’s make the problem more interesting; you might want to highlight the international dialing code in a different colour, or, if the application is being used by a UK client, display the number in a local format without the international code ‘0845 2241930′. So just how do we achieve this?

In order to break the number up into different blocks of text, with different colours (i.e. styles), we need to modify our view to have multiple TextBlocks mapped to the PhoneNumber property of our business object. The part of our view which renders the phone number is modified as follows:

<StackPanel Orientation="Horizontal">
    <TextBlock Text="p: "/>
    <TextBlock Text="... country code ..." Foreground="LightGray"/>
    <TextBlock Text="... area code ..."/>
    <TextBlock Text="... local number ..."/>
</StackPanel>

But just how exactly do we bind the properties of these business objects?

One approach would be to use a value converter for each binding in order to extract the required part of the number, for example a CountryCodeValueConverter could be implemented which grabs the first 2 digits of the number. However, this approach is a little inelligent in that it fragments our logic into a number of separate classes, furthermore, if we want country specific formatting this requires the use of multibindings, which can be rather cumbersome if over-used (for a Silverlight implementation of multi bindings see my blog post from earlier this year).

Another approach which is often used to tackle tricky binding problems is the use of the Model-View-ViewModel (MVVM) pattern. With this pattern, our ContactDetails object is the Model, we construct a ViewModel which is a UI-oriented abstraction of the Model and it is this which we bind to the View. WPF guru Josh Smith describes MVVM as “a value converter on steroids” in order to highlight the usefulness of the pattern in this context.

The basic approach used here is to bind your View to a ViewModel rather than binding it to the business object directly. The ViewModel is specific to the view and wraps the business object (i.e. Model), forwarding the property values and change notification to the View. This extra layer allows us to supplement the properties of the Model object, adding new computed properties which are specific to the View. In this case, these computed properties can be used to expose ‘country code’, ‘area code’, etc… to our View.

(This is a common pattern so I am not going to reproduce the code required here, however, if you are interested, the attached sourcecode accompanying this article contains a regular ViewModel version as well as a mini-ViewModel implementation)

Whilst this approach works, my issue with it is that it adds quite a bit of boiler-plate code for wrapping properties, forwarding events etc … The removal of this glue-code is the exact reason that I like WPF/Silverlight so much! The MVVM pattern is primarily for supporting the designer-developer paradigm and enabling unit testing of UI applications, in my opinion the use of MVVM for anything else is just plain wrong!

So, how can we solve the problem of providing a nicely formatted phone number without the pain of bashing out line-after-line line of boiler-plate MVVM code? My solution to the problem isn’t to dispose of the MVVM pattern altogether, rather, it is to localise its usage to just the problem area. The first step is to encapsulate the rendering of the phone number as a user control:

...
<StackPanel Orientation="Horizontal">
    <TextBlock Text="p: "/>
    <local:PhoneNumberControl Number="{Binding PhoneNumber}" />
</StackPanel>
...

… which probably makes sense anyway from a perspective of good design and code re-use!

Now that we have moved the phone number property within the PhoneNumberControl we have isolated the problem and can deal with it locally. We can create a PhoneNumberControlViewModel which splits the phone number up into its various components and bind this to the PhoneNumberControl.

The control’s ViewModel looks something like this:

public class PhoneNumberControlViewModel : INotifyPropertyChanged
{
    public PhoneNumberControlViewModel(PhoneNumberControl ctrl)
    {
        _ctrl = ctrl;
        ComputeProperties();
 
        // listen to property changes in the control (we are interested
        // in just the Number property)
        _ctrl.PropertyChanged += Control_PropertyChanged;
    }
 
    private PhoneNumberControl _ctrl;
 
    private string _countryCodeText;
 
    private string _areaCodeText;
 
    private string _localNumberText;
 
    public string CountryCodeText
    {
        get { return _countryCodeText; }
        set { _countryCodeText = value; OnPropertyChanged("CountryCodeText");  }
    }
 
    public string AreaCodeText
    {
        get { return _areaCodeText; }
        set { _areaCodeText = value; OnPropertyChanged("AreaCodeText"); }
    }
 
    public string LocalNumberText
    {
        get { return _localNumberText; }
        set { _localNumberText = value; OnPropertyChanged("LocalNumberText"); }
    }
 
    private void Control_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "Number" || e.PropertyName == "Country")
        {
            ComputeProperties();
        }
    }
 
    private void ComputeProperties()
    {
        string formattedNumber = _ctrl.Number.ToString();           
        CountryCodeText = "+" + formattedNumber.Substring(0, 2);
        AreaCodeText = " (" + formattedNumber.Substring(2, 1) + ")" + formattedNumber.Substring(3, 3);
        LocalNumberText = " " + formattedNumber.Substring(6);
    }
}

Note that here the ViewModel is ‘wrapping’ the PhoneNumberControl rather than an instance of some Business / Model object.

Now we just set our ViewModel as the DataContext for the View, as per the typical usage of this pattern:

public PhoneNumberControl()
{
    InitializeComponent();
 
    this.DataContext = new PhoneNumberControlViewModel(this);
}

… and it doesn’t work. If you try the above, you will find that the binding on the PhoneNumberControls Number property no longer works. So why is this? if you look back at where the PhoneNumberControl instance is defined in our business card’s XAML markup you see that its Number property is bound as follows:

<local:PhoneNumberControl Number="{Binding PhoneNumber}" />

The source of this binding is not explicitly set, so will default to using the DataContext of the PhoneNumberControl instance. However, we have just changed this DataContext in our constructor to something else … oops!

Solving this problem is actually quite simple, the PhoneNumberControl markup is as follows:

<UserControl x:Class="SLMiniViewModel.PhoneNumberControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel x:Name="LayoutRoot" Orientation="Horizontal">
        <TextBlock Text="{Binding CountryCodeText}" Foreground="DarkGray"/>
        <TextBlock Text="{Binding AreaCodeText}"/>
        <TextBlock Text="{Binding LocalNumberText}"/>
    </StackPanel>
</UserControl>

If we modify our binding to the ViewModel as follows:

public PhoneNumberControl()
{
    InitializeComponent();
 
    LayoutRoot.DataContext = new PhoneNumberControlViewModel(this);
}

The subtle difference being that the ViewModel is now bound to the StackPanel which is the root of our visual tree within the control. This means that the PhoneNumberControl DataContext is still inherited from the business card and is our business object instance, the DataContext switch to the ViewModel is now neatly tucked just within the PhoneNumberControls visual tree, and it is this DataContext which our TextBlocks will inherit and bind to.

The result is that we can now use our mini-ViewModel embedded within the PhoneNumberControl to expose properties which are more amenable to binding to our View:

card2

Whilst this is a quite trivial example, in real-world applications, more complex examples where the data representation within the View is dependant on a number of properties are quite common. The source code accompanying this article extends the example a little further by making the formatting dependant on a second property of the business object. This is the sort of problem that would either push you towards multi-binding and numerous fragmented value converters, or a ViewModel.

In conclusion, the use of a mini-ViewModel which is embedded within a UserControl allows you to solve tricky binding problems without being weighed down by rolling out the MVVM pattern across your entire View. I am not against the MVVM pattern in itself, however I do firmly believe that it should only be used to solve the problems which it is was specifically designed for, i.e. supporting the designer-developer workflow and unit testing.

You can download the source-code for this article: SLMiniViewModel.zip – this project contains both MVVM and mini-MVVM implementations (count the number of lines in the ViewModel and contrast it with the mini-ViewModel).

Regards, Colin E.