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}">
     <Button.CommandParameter>
          <MultiBinding Converter="{StaticResource ShinyToAwesomeConverter}">
               <Binding Path="ShinyItem"/>
          </MultiBinding>
     </Button.CommandParameter>
</Button>

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s