Click here to Skip to main content
Click here to Skip to main content
Go to top

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

, 15 Jun 2010
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.

app.png

[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:BindingUtil.MultiBinding>
        <local:MultiBinding TargetProperty="Text" 
		Converter="{StaticResource TitleConverter}">
            <Binding Path="Surname"/>                            
            <Binding Path="Forename"/>
        </local:MultiBinding>
    </local:BindingUtil.MultiBinding>
</TextBlock>
 
<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:

multibinding

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>
</span>/// Invoked when the MultiBinding property is set on a framework element
/// <span class="code-SummaryComment"></summary>
</span>private static void OnMultiBindingChanged(DependencyObject depObj,
  DependencyPropertyChangedEventArgs e)
{
  FrameworkElement targetElement = depObj as FrameworkElement;
 
  // bind the target elements DataContext, to our DataContextPiggyBack property
  // this allows us to get property changed events when the targetElement
  // DataContext changes
  targetElement.SetBinding(BindingUtil.DataContextPiggyBackProperty, new Binding());
}
 
public static readonly DependencyProperty DataContextPiggyBackProperty =
    DependencyProperty.RegisterAttached("DataContextPiggyBack",
        typeof(object), typeof(BindingUtil), new PropertyMetadata(null,
              new PropertyChangedCallback(OnDataContextPiggyBackChanged)));
 
public static object GetDataContextPiggyBack(DependencyObject d)
{
  return (object)d.GetValue(DataContextPiggyBackProperty);
}
 
public static void SetDataContextPiggyBack(DependencyObject d, object value)
{
  d.SetValue(DataContextPiggyBackProperty, value);
}
 
/// <span class="code-SummaryComment"><summary>
</span>/// Handles changes to the DataContextPiggyBack property.
/// <span class="code-SummaryComment"></summary>
</span>private static void OnDataContextPiggyBackChanged(DependencyObject d,
                                                  DependencyPropertyChangedEventArgs e)
{
  FrameworkElement targetElement = d as FrameworkElement;
 
  // whenever the targeElement DataContext is changed, copy the updated property
  // value to our MultiBinding.
  MultiBinding relay = GetMultiBinding(targetElement);
  relay.DataContext = targetElement.DataContext;
}

Creating Targets for the Bindings

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

[ContentProperty("Bindings")]
public class MultiBinding : Panel, INotifyPropertyChanged
{
  ...
 
  /// <span class="code-SummaryComment"><summary>
</span>  /// The bindings, the result of which are supplied to the converter.
  /// <span class="code-SummaryComment"></summary>
</span>  public ObservableCollection<Binding> Bindings { get; set; }
 
  ...
}

(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>
</span>/// Creates a BindingSlave for each Binding and binds the Value
/// accordingly.
/// <span class="code-SummaryComment"></summary>
</span>internal void Initialise()
{
  foreach (Binding binding in Bindings)
  {
    BindingSlave slave = new BindingSlave();
    slave.SetBinding(BindingSlave.ValueProperty, binding);
    slave.PropertyChanged += new PropertyChangedEventHandler(Slave_PropertyChanged);
    Children.Add(slave);
  }            
}

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>
</span>/// Invoked when any of the BindingSlave's Value property changes.
/// <span class="code-SummaryComment"></summary>
</span>private void Slave_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
  List<object> values = new List<object>();
  foreach (BindingSlave slave in Children)
  {
    values.Add(slave.Value);
  }
  ConvertedValue = Converter.Convert(values.ToArray(), typeof(object), ConverterParameter,
    CultureInfo.CurrentCulture);
}

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:

virtualbranch

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.

License

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

Share

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
 
-
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralForce Update PinmemberLuka21-Apr-11 5:05 
NewsSilverlight 4 PinmemberColin Eberhardt15-Jun-10 21:55 
GeneralSL 4 PinmemberVossG21-Mar-10 10:02 
GeneralRe: SL 4 Pinmember[PyRaMiD]9-Apr-10 14:04 
GeneralRe: SL 4 PinmemberSilenceTi19-Apr-10 5:07 
AnswerRe: SL 4 PinmemberColin Eberhardt19-Apr-10 23:55 
GeneralRe: SL 4 Pinmembermiguel.luna22-Apr-10 2:02 
GeneralRe: SL 4 PinmemberColin Eberhardt22-Apr-10 2:08 
GeneralAnother approach PinmemberMarcel Pletosu21-Dec-09 8:08 
GeneralRe: Another approach PinmemberColin Eberhardt24-Dec-09 0:50 
GeneralGreat article Pinmembereslsys30-Jun-09 2:13 
GeneralRe: Great article PinmemberColin Eberhardt30-Jun-09 2:21 
Generalgreat article, and smart MVVM statement Pinmemberchristoph braendle25-Jun-09 23:52 
GeneralRe: great article, and smart MVVM statement PinmemberColin Eberhardt26-Jun-09 0:10 
GeneralRe: great article, and smart MVVM statement PinmvpPete O'Hanlon28-Jun-09 11:07 
GeneralThis is one helluva article PinmvpPete O'Hanlon25-Jun-09 11:39 
GeneralRe: This is one helluva article PinmemberColin Eberhardt25-Jun-09 21:08 
GeneralRe: This is one helluva article PinmvpPete O'Hanlon26-Jun-09 3:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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 | Mobile
Web02 | 2.8.140926.1 | Last Updated 16 Jun 2010
Article Copyright 2009 by Colin Eberhardt
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid