Click here to Skip to main content
12,296,307 members (63,629 online)
Click here to Skip to main content
Add your own
alternative version


53 bookmarked

Silverlight MultiBindings, How to attach multiple bindings to a single property.

, 15 Jun 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
This blog post describes a technique for associating multiple bindings with a single dependency property within Silverlight applications. WPF already has this functionality in the form of MultiBindings, the code in this post emulates this function.

This blog post describes a technique for associating multiple bindings with a single dependency property within Silverlight applications. WPF already has this functionality in the form of MultiBindings, the code in this post emulates this function. 

UPDATE: This blog post has attached code for Silverlight 3, for Silverlight 4 users please see my blog for the updated code

The simple application below demonstrates this technique, where there are three data-entry text boxes bound to the individual properties of a simple Person object, with the title text block being bound to both the Forename and Surname properties. Try editing the surname or forename fields and watch as the title is updated.


[CodeProject does not support Silverlight applets, see the above applicaton in action on my blog.]

The XAML for this application looks something like this (superfluous properties/ elements removed for clarity):

<TextBlock Foreground="White" FontSize="13">
        <local:MultiBinding TargetProperty="Text" 
		Converter="{StaticResource TitleConverter}">
            <Binding Path="Surname"/>                            
            <Binding Path="Forename"/>
<TextBlock Text="Surname:"/>
<TextBox  Text="{Binding Path=Surname, Mode=TwoWay}"/>
<TextBlock Text="Forename:"/>
<TextBox Text="{Binding Path=Forename, Mode=TwoWay}"/>
<TextBlock Text="Age:"/>
<TextBox Text="{Binding Path=Age, Mode=TwoWay}"/>

The Solution

My solution to the problem of multi-binding was to introduce a class, MultiBinding which is associated with the element which has out multi-binding target property via the BindingUtil.MultiBinding attached property. The following diagram details my idea:


The Forename and Surname bindings are bound to properties of the MultiBinding (exactly which properties we will get onto in a minute). The MultiBinding has an associated Converter of type IMultiValueConverter, this client supplied class implements the conversion process, as shown below:

public class TitleConverter : IMultiValueConverter
  public object Convert(object[] values, Type targetType,
    object parameter, System.Globalization.CultureInfo culture)
    string forename = values[0] as string;
    string surname = values[1] as string;
    return string.Format("{0}, {1}", surname, forename);

The IMultiValueConverter interface is much the same as the IValueConverter, except in this case an array of objects are passed to the converter, with each object containing the current bound value for each of our bindings in order.

With this value converter, the MultiBinding class can detect changes in the two bindings, then, recompute the ConvertedValue which is bound to the target property of our TextBlock. This was my initial idea, and it certainly sounds quite simple, however it was not quite as easy as it seems on first inspection!

Hijacking the DataContext

Typically when defining a binding, we omit the Source property, e.g. {Binding Path=Forename}. When the Binding which this expression represents is associated with an element, the binding source will be the (possibly inherited) DataContext of the target element. Therefore, in order to allow binding on the MultiBinding class, it must be a FrameworkElement, this gives us the DataContext property and the SetBinding() method.

However, there is a problem; each element’s DataContext is inherited from its parent within the visual tree. Our MultiBinding is not within the visual tree and we do not want it to be, therefore it will not participate in DataContext inheritance. What we need to do is ensure that when DataContext changes on the element which the MultiBinding is associated with it, that we ‘push’ this DataContext onto the MultiBinding. With WPF this is easy, FrameWorkElement exposes a DataContextChanged event, (for DPs that do not expose events, there’s always the DependencyPropertyDescriptor). However, with Silverlight, neither of these options is available.

My solution here is to create a new attached property and attach it to the target element (our TextBlock in this case), which piggy-backs the DataContext. The code below is from the BindingUtil class, when the MultiBinding class is associated with the target element as an attached property, we also bind its attached DataContextPiggyBack property. We define a static method which is invoked whenever the DatatContext of the target element changes, and here we ‘push’ this new DataContext to the MultiBinding class.

/// <span class="code-SummaryComment"><summary>

Creating Targets for the Bindings

The MultiBinding class needs to have a property which is a collection of type Binding:

public class MultiBinding : Panel, INotifyPropertyChanged
  /// <span class="code-SummaryComment"><summary>

(Note the use of the ContentProperty attribute, which means that we do not have to explicitly detail Binding collection in XAML using the property element syntax). The problem is, in order for these bindings to be evaluated, they need to be bound to a target property. We could add a number of ‘dummy’ properties to MultiBinding, PropertyOne, PropertyTwo, etc … and bind to these, however this approach is cumbersome and limited.

The solution here is to make MultiBinding a Panel, this allows it to have child elements, each of which will inherit its DataContext. When the MultiBinding class is initialised at the point it is attached, the Initialise method is invoked. This method creates an instance of BindingSlave, a simple FrameworkElement subclass with a single Value property which raises PropertyChanged events when this property changes, for each binding:

/// <span class="code-SummaryComment"><summary>

Whenever a slave property changes, the MultiBinding event handler obtains the current bound values and uses them to re-evaluate the converter:

/// <span class="code-SummaryComment"><summary>

The ConvertedValue property is bound to the target property of the target element, and will be updated to reflect this change.

This method is very similar to the one which Josh Smith described in his CodeProject article on the concept of Virtual Branches. The MultiBinding and BindingSlave instances can be thought of as a virtual branch to our visual tree:


Download Sources

You can download the full source code for this project here.

A Final Word on MVVM

The MVVM pattern is very popular in Silverlight and WPF application development. With this pattern, your view’s DataContext is bound to your view-model. With this pattern in place, the need for multi-bindings can be removed (Josh Smith goes further to moot the concept of removing value converters altogether). In our example, the PersonViewModel class would simply expose a Title property which performs the same function as the TitleConverter. So does this render my technique completely redundant?

I don’t think so. Whilst MVVM is a great pattern, there are times where adding another layer to your application may be undesirable, especially if your primary aim is simplicity. Furthermore, I do not like being forced into using a specific pattern simply because the framework itself is lacking in functionality. The MVVM pattern is great for building skinnable applications, and allowing UI unit testing, however, if I do not need either of these features, I would prefer not to MVVM.

Regards, Colin E.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Colin Eberhardt
Architect Scott Logic
United Kingdom United Kingdom
I am CTO at ShinobiControls, a team of iOS developers who are carefully crafting iOS charts, grids and controls for making your applications awesome.

I am a Technical Architect for Visiblox which have developed the world's fastest WPF / Silverlight and WP7 charts.

I am also a Technical Evangelist at Scott Logic, a provider of bespoke financial software and consultancy for the retail and investment banking, stockbroking, asset management and hedge fund communities.

Visit my blog - Colin Eberhardt's Adventures in .NET.

Follow me on Twitter - @ColinEberhardt


You may also be interested in...

Comments and Discussions

GeneralForce Update Pin
Luka21-Apr-11 5:05
memberLuka21-Apr-11 5:05 
NewsSilverlight 4 Pin
Colin Eberhardt15-Jun-10 21:55
memberColin Eberhardt15-Jun-10 21:55 
GeneralSL 4 Pin
VossG21-Mar-10 10:02
memberVossG21-Mar-10 10:02 
GeneralRe: SL 4 Pin
[PyRaMiD]9-Apr-10 14:04
member[PyRaMiD]9-Apr-10 14:04 
GeneralRe: SL 4 Pin
SilenceTi19-Apr-10 5:07
memberSilenceTi19-Apr-10 5:07 
AnswerRe: SL 4 Pin
Colin Eberhardt19-Apr-10 23:55
memberColin Eberhardt19-Apr-10 23:55 
GeneralRe: SL 4 Pin
miguel.luna22-Apr-10 2:02
membermiguel.luna22-Apr-10 2:02 
GeneralRe: SL 4 Pin
Colin Eberhardt22-Apr-10 2:08
memberColin Eberhardt22-Apr-10 2:08 
It certainly looks like there is a lot of demand for this!

Yes, I will upgrade for SL4. I will try to do it in the next week.

Colin E.
GeneralAnother approach Pin
Marcel Pletosu21-Dec-09 8:08
memberMarcel Pletosu21-Dec-09 8:08 
GeneralRe: Another approach Pin
Colin Eberhardt24-Dec-09 0:50
memberColin Eberhardt24-Dec-09 0:50 
GeneralGreat article Pin
eslsys30-Jun-09 2:13
membereslsys30-Jun-09 2:13 
GeneralRe: Great article Pin
Colin Eberhardt30-Jun-09 2:21
memberColin Eberhardt30-Jun-09 2:21 
Generalgreat article, and smart MVVM statement Pin
christoph braendle25-Jun-09 23:52
memberchristoph braendle25-Jun-09 23:52 
GeneralRe: great article, and smart MVVM statement Pin
Colin Eberhardt26-Jun-09 0:10
memberColin Eberhardt26-Jun-09 0:10 
GeneralRe: great article, and smart MVVM statement Pin
Pete O'Hanlon28-Jun-09 11:07
mvpPete O'Hanlon28-Jun-09 11:07 
GeneralThis is one helluva article Pin
Pete O'Hanlon25-Jun-09 11:39
mvpPete O'Hanlon25-Jun-09 11:39 
GeneralRe: This is one helluva article Pin
Colin Eberhardt25-Jun-09 21:08
memberColin Eberhardt25-Jun-09 21:08 
GeneralRe: This is one helluva article Pin
Pete O'Hanlon26-Jun-09 3:02
mvpPete O'Hanlon26-Jun-09 3:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160525.2 | Last Updated 16 Jun 2010
Article Copyright 2009 by Colin Eberhardt
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid