Nested MultiBinding(s)

Louis Kottmann picture Louis Kottmann · Apr 23, 2012 · Viewed 7.9k times · Source

I've been playing around with WPF for quite a while now, but for the first time today, I needed to nest a MultiBinding inside another, something like:

<MultiBinding>
   <Binding />       
   <MultiBinding>
      <Binding />
      <Binding />
   </MultiBinding>
</MultiBinding>

I get an exception indicating it's not allowed by the framework:

XamlParseException was unhandled: Add value to collection of type 'System.Collections.ObjectModel.Collection(System.Windows.Data.BindingBase)' threw an exception.

The InnerException is more explicit:

BindingCollection does not support items of type MultiBinding. Only Binding is allowed.

So digging the web for more info, I stumbled upon this Microsoft Connect issue which is exactly my problem.

Thank you for the feedback. WPF doesn't support this today. This feature has been requested for years (most recently earlier this month - see https://connect.microsoft.com/WPF/feedback/details/650164/nested-multibinding). We'll continue to consider this for future releases.

Right now I've made my peace that I won't have it easy. Still I need this, how can I nest MultiBindings?

Answer

Dan Puzey picture Dan Puzey · Apr 23, 2012

If you have a converter that takes a parameter, you can do something like this:

  • Create a class for passing the "fixed" data to your converter
  • Add DependencyProperties to the class (so that you can bind the values in Xaml)
  • In your xaml, use a binding with a converter instead of a multibinding, something like this:

    <MultiBinding>
        <Binding Source="SomeObject" Path="CoreValue" Converter="{StaticResource YourNewConverter}">
            <Binding.ConverterParameter>
                <ns:ParameterClass Value1="{Binding Parameter1}" Value2="{Binding Parameter1}" />
            </Binding.ConverterParameter>
        </Binding>
     .... 
    

The limitation is that (AFAIK) the value will only be recalculated if CoreValue changes - it won't automatically rebind if the converter parameters change.

(Apologies for any errors, I'm typing this without the benefit of VS to test in...)