My wish came true…. I can now use DataBinding in a ConverterParameter

WARNING: This solution uses reflection so it cannot be used in XBAP or applications running with Partial Trust.

One of the things I hear often in forums and also lately on the WPF Disciples mailing list is, “How come I cannot use binding in ConverterParameters?” or “My personal pet peeve is the ConverterParameter. Ah if I could only bind it to something in my ViewModel!!”

So let’s start by seeing why you cannot use binding for a ConverterParameter. The simple answer to that would be, a ConverterParameter is not a DependencyProperty thus you cannot use Binding. Yet the following question would be, WHY isn’t it a DependencyProperty?? Well there are a few things we must have a look at here. First of all the Binding class is not a DependencyObject. Secondly the BindingBase class seals itself when the binding activates, this means that once the Binding is activated you cannot change any properties. If you try to do so you get a nice InvalidOperationException saying “Binding cannot be changed after it has been used”.

Yet, the WPF platform is very flexible so I decided to start digging into it and see what I can come up with (obviously always consulting the WPF KING OF KINGS, Dr.WPF).

The first idea…

My first idea was to create a MarkupExtension that spits out an instance of an object that has a Dependency Property that you can bind with (some sort of Proxy that can update the Binding and specify a new value). So your XAML would look like this

{Binding ElementName=checkbox1, Path=IsChecked, Converter={StaticResource conv}, ConverterParameter={code:BindableParameter {Binding ElementName=checkbox2, Path=IsChecked}} }

Yet this failed miserably because of a simple yet hard problem in the design I had. You cannot get the BindingExpression of that binding because the BindingExpression is not constructed yet. I could get the Binding instance but the Binding instance alone is nothing without the BindingExpression since you can update a binding by calling the UpdateSource method of the Binding expression.

Back to the drawing boards…. and finally the Solution

So let’s have a look at what we want to achieve. We want to

1. Let the User Specify a Binding for a ConverterParameter somewhere in the XAML
2. Make sure that when a value of the ConverterParameter changes the original Binding gets updated.

In order to solve problem 1, I decided to go to my best friend, AttachedProperties. Basically the idea is that you set an attached property that specifies the value of a ConverterParameter of a specific binding. So the XAML would look something like this

   1: <ToggleButton Content="I am bound to the checkbox" x:Name="toggle"
   2:      code:BindableParameter.BindParameter="{code:BindableParameter ToggleButton.IsChecked, Binding={Binding ElementName=checkbox2, Path=IsChecked}}"
   3:      IsChecked="{Binding Converter={StaticResource conv}, ElementName=checkbox1, Path=IsChecked}"/>

In the attached property you specify what Binding you want to target by supplying the DependencyProperty to which the original Binding is applied. In this case the original Binding is for the IsChecked property of the ToggleButton. Then you can simple specify the Binding you want for the ConverterParameter by setting the Binding property of the BindableParameter markup extension.

Now that you have supplied this information, the BindableParameter can do some tricks for you. Basically once you specify the BindParameter attached property the BindableParameter will get a BindingExpression for the original binding and make sure to set the ConverterParameter when ever needed. Have a look at the PropertyChanged event handler of the BindParameter Attached property.

   1: private static void OnBindParameterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   2: {
   3:     FrameworkElement element = d as FrameworkElement;
   4:     if (element == null)
   5:         throw new InvalidOperationException("BindableParameter can be applied to a FrameworkElement only");
   7:     BindableParameter parameter = (BindableParameter)e.NewValue;
   8:     element.Initialized += delegate
   9:     {
  10:         parameter.TargetExpression = BindingOperations.GetBindingExpression(element, parameter.TargetProperty);
  11:         parameter.TargetBinding = BindingOperations.GetBinding(element, parameter.TargetProperty);
  13:         //update the converter parameter 
  14:         InvalidateBinding(parameter);
  15:     };
  16: }

As you can see, in the above code, all we are doing is get the instance of the BindingExpression and storing it in an instance variable(TargetExpression). Same goes for the Binding, storing it in the TargetBinding. Now that we have all this information we can do Step 2 (Make sure that when a value of the ConverterParameter changes the original Binding gets updated)

In the Property Changed event handler of the Binding we must force the BindingExpression to update and change the value of the converter parameter. This can be done quite easily one would say but there are 2 main problems.

Problem 1. How to make the binding work for the BindableParamater?? The BindableParameter is not in the LogicalTree because it is just a DependencyObject thus the Binding that you set will not be valid. In order to overcome this issue we can do a little trick with the Freezable class. If we make the BindableParameter inherit from the Freezable it gets the inheritance context thus Binding is now valid. For more info on this technique visit Dr. WPF blog

Problem 2. How can we change the value of ConverterParameter if the Binding is sealed (remember? the Binding class will throw an InvalidOperationException if we try to change a property of the Binding). This problem required me to do some hard core disassembling of the Binding class and I found out that each Property Setter of the Binding class has a call to a method CheckSealed. This method looks like this

   1: internal void CheckSealed()
   2: {
   3:     if (this._isSealed)
   4:     {
   5:         throw new InvalidOperationException(SR.Get("ChangeSealedBinding"));
   6:     }
   7: }

So what we must do is to get the _isSealed Field info by reflection and change it’s value to false, then change the ConverterParameter and finally put the _isSealed value back to true so that WPF does not notice us playing tricks on him 🙂
Once we do that we are free to change the value of the ConverterParameter and we can Refresh the Binding

Something like this

   1: private static void InvalidateBinding(BindableParameter param)
   2: {
   3:     if (param.TargetBinding != null && param.TargetExpression != null)
   4:     {
   5:         //this is a hack to trick the WPF platform in thining that the binding is not sealed yet and then change the value of the converter parameter
   6:         bool isSealed = (bool)isSealedFieldInfo.GetValue(param.TargetBinding);
   8:         if (isSealed)//change the is sealed value
   9:             isSealedFieldInfo.SetValue(param.TargetBinding, false);
  11:         param.TargetBinding.ConverterParameter = param.ConverterParameterValue;
  13:         if (isSealed)//put the is sealed value back as it was...
  14:             isSealedFieldInfo.SetValue(param.TargetBinding, true);
  16:         //force an update to the binding
  17:         param.TargetExpression.UpdateTarget();
  18:     }
  19: }

And there it is …. I can now use binding for a ConverterParameter and the XAML looks like this

   1: <Window.Resources>
   2:    <code:DummyConverter x:Key="conv"/>
   3: </Window.Resources>
   4: <StackPanel>
   5:    <CheckBox x:Name="checkbox2" Content="I am the parameter for the converter"/>
   6:    <CheckBox x:Name="checkbox1" Content="I am bound directly"/>
   8:    <ToggleButton Content="I am bound to the checkbox" x:Name="toggle"
   9:                  code:BindableParameter.BindParameter="{code:BindableParameter ToggleButton.IsChecked, Binding={Binding ElementName=checkbox2, Path=IsChecked}}"
  10:                  IsChecked="{Binding Converter={StaticResource conv}, ElementName=checkbox1, Path=IsChecked}"/>
  11: </StackPanel>

Hope you enjoy this …..


kick it on