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");
   6:
   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);
  12:
  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: }
   8:

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);
   7:
   8:         if (isSealed)//change the is sealed value
   9:             isSealedFieldInfo.SetValue(param.TargetBinding, false);
  10:
  11:         param.TargetBinding.ConverterParameter = param.ConverterParameterValue;
  12:
  13:         if (isSealed)//put the is sealed value back as it was...
  14:             isSealedFieldInfo.SetValue(param.TargetBinding, true);
  15:
  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"/>
   7:
   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 …..

DOWNLOAD SOURCE CODE

kick it on DotNetKicks.com

18 thoughts on “My wish came true…. I can now use DataBinding in a ConverterParameter

  1. What a creative approach, Marlon! (And I thought I was a hacker!!)

    I did a little reflection, and it looks like your approach should be reliable in the current release since the ConverterParameter property is never cached internally. Nice job! Keep us posted on how this works in your projects. 🙂

  2. Very cool!

    Why not allow this to work for FrameworkContentElements too? I saw that you throw an exception if you set this on anything but an FE, but is there a reason why you exclude FCEs?

    I suggest that when using reflection to hack into WPF, you mention in the beginning of the post that this technique uses reflection. This will immediately let people know that they cannot use the trick in the standard XBAPs, or any WPF app that runs with partial trust.

    Josh

  3. RE: the FrameworkContentElements, there was no reason not to support them …. just a silly mistake….

    I will update the post to say that this has reflection… THanks dude!!!!

  4. nice one… I like it… Yet the only problem (not really a problem) would be that you would receive an instance of the proxy class in the ConverterParameter….

    I like your solution 😀 cool!

  5. I find this approach confusing to read, hard to follow, and not worthwhile to maintain.

    Sorry, Marlon, I applaud your ingenuity but it just isn’t good enough.

    Just supplying counter-feedback in the face of elated masses. Someone has to put their foot down and say “No!” to these hacks and unnecessary complexity. Anyone using these hacks should just jump aboard a petition to make ConverterParameter a DependencyObject.

    • Your s dumb sob. ROFL THERE IS NO CODE SOLUTION AS THE LINK, Robert Hormozi just how long have you been sticking that unit incher of yours up a goats ahole

  6. John “Z-Bo” Zabroski , I must say I agree with you… this is way complicated… if you ever need to do something similar use MultiBinding not this solution.

    I am a geek, I love cool stuff… and that is why I created this…. what do you want me to do on a Sunday morning ?? 😛

  7. I dislike the MultiBinding ME as well. It forces me to remember the order of arguments, instead of simply passing in named parameters. I find this peculiar, since XAML was intended for tool-ability, yet Binding’s are very much a black box design. It also highlights an oversight in XAML’s design that took some ingenuity to overcome: lack of a concise way to specify a Map. I chose to create my own mini-language for this, based on Common Lisp-style linked list representations of name/value pairs.

    I’m a colossal geek as well, but I’m trying to build long-term, zero-defect GUI applications. I selected WPF largely because a number of features help this greatly, yet the core WPF team has been slow to respond to community acknowledgment that some basic improvements can and should be made.

  8. Hi Marlon,
    I recently solved a problem that required binding the ConverterParameter.
    I solved it by using a MultiBinding instead of a Binding with an IMultiValueConverter instead of a IValueConverter.
    Wouldnt this be a good solution in every case?
    David

  9. Here is one way you can bind in a ConverterParameter. Set the content of the ConverterParameter to an object that can bind. At least this works in Silverlight 4.

  10. yea the guy is fucking lieing sob who copy and paste crap just o show he sucks the homo dicl

  11. Pingback: C#学习教程:如何简单地将其绑定到ConverterParameter?分享-安普网

Leave a comment