Category: Code Snippet

WPF Snippet – Setting a Binding on a Converter Parameter Property

A somewhat techy post today.

I came across a problem at work recently – I was attempting to bind the result of a converter to the command parameter of a button. Note that below code is written as an example of what I was attempting, and isn’t actually live code anywhere. Hopefully, my fantastic naming convention will give that away.

Here’s what *didn’t* work:

<Button Command="{Binding AwesomeCommand}" CommandParameter="{Binding Converter={StaticResource ShinyToAwesomeConverter}, ConverterParameter={Binding ShinyItem}}"/>

This threw up an error:

a ‘Binding’ cannot be set on the ‘ConverterParameter’ property of type ‘Binding’

After some googling around, it turns out that the solution is to use a multibinding converter. My converter was updated to implement IMultiValueConverter, and became the following:

public class ShinyToAwesomeConverter : IMultiValueConverter
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
           if (!(values[0] is Shiny))
              throw new ArgumentException("Value should be Shiny.");

           return new Awesome(values[0] as Shiny);

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
           throw new NotImplementedException();

I then updated my xaml as follows:

<Button Command="{Binding AwesomeCommand}">
          <MultiBinding Converter="{StaticResource ShinyToAwesomeConverter}">
               <Binding Path="ShinyItem"/>

So there you have it. Use a multibinding converter to bind a value to a converter parameter.