Silverlight 4 Multi-Binding Converter Enhancement

September 15, 2011 • Damien White

We have been using Colin Eberhardt’s MultiBinding Converter for Silverlight for quite a while now. It was great until we realized a problem. When the MultiBinding Converter was off screen (hidden), it would throw a binding error stating that it couldn’t convert null to whatever (in our case it was an integer in one converter and FontWeight in another).

The Solution

The solution is rather easy. Add a property called TargetNullValue to MultiBinding.cs in Colin’s source. There’s no “magic” in this name, you can call it whatever you want. TargetNullValue seems to make the most sense for its purpose in this case, and is the name of the property on the actual Silverlight Binding that we’ll be setting in the next step.

/// <summary>
/// Gets or sets the target null value.
/// </summary>
public object TargetNullValue { get; set; }

Then, hop over to MulitBindings.cs and change the binding (line 110) to utilize the TargetNullValue property on the binding for the ConvertedValue like so:

// bind the ConvertedValue of our MultiBinding instance to the target property
// of our targetElement
Binding binding = new Binding("ConvertedValue")
{
  Source = relay,
  Mode = relay.Mode,
  TargetNullValue = relay.TargetNullValue
};

Now, when you use the MultiBinding, just fill in the TargetNullValue property, for example:

<TextBlock ...>
    <multi:BindingUtil.MultiBindings>
        <multi:MultiBindings>
            <multi:MultiBinding TargetProperty="FontWeight" TargetNullValue="Normal" Converter=...>
                <multi:MultiBinding.Bindings>
                    <multi:BindingCollection>
                        ...
                    </multi:BindingCollection>
                </multi:MultiBinding.Bindings>
            </multi:MultiBinding>
        </multi:MultiBindings>
    </multi:BindingUtil.MultiBindings>
</TextBlock>

Now my Debug Output window isn’t filled with needless binding errors!

Posted in .net, c#, silverlight and tagged with Silverlight

Damien White

I am a software architect with over 16 years of experience. I simply love coding! I have a driving passion for computers and software development, and a thirst for knowledge that just cannot be quenched. I'm happy to share what I know in my quest to learn as much as possible. I focus most of my time on web development using Ruby on Rails, Ember.js, and ASP.NET MVC.

comments powered by Disqus