1

Most converters take no parameters, or one fixed parameter, and are easy to bind to:

<local:MyConverter x:Key="MyConverterInstance" />

<TextBox Text="{Binding Path=MyTime, 
                        Converter={StaticResource MyConverterInstance},
                        ConverterParameter='yyyy/MM/dd'}" />

But if I want that format to be a dynamic property that the user can change, I can't do something like this, right?:

<TextBox Text="{Binding Path=MyTime, 
                        Converter={StaticResource MyConverterInstance},
                        ConverterParameter={Binding Path=UserFormat}}" />

So my only option is to define a DependencyProperty on MyConverter for binding. But my converter definition is a StaticResource. I can't go

<local:MyConverter x:Key="MyConverterInstance" 
                   Format="{Binding Path=UserFormat}"/>

because there's no DataContext on StaticResources. How can I set this up?

Alain
  • 26,663
  • 20
  • 114
  • 184

1 Answers1

5

You cannot bind to a converterparameter but you can use Multibinding instead. For example: http://www.switchonthecode.com/tutorials/wpf-tutorial-using-multibindings or How to simply bind this to ConverterParameter?

(Alain) So just to translate that linked answer into something that matches this question:

<TextBlock>
    <TextBlock.Resources>
        <local:MyConverter x:Key="MyConverterInstance" />
    </TextBlock.Resources>
    <TextBlock.Text>
        <MultiBinding Converter="{StaticResource converter}">
            <Binding Path="MyTime" />
            <Binding Path="UserFormat" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

public class MyConverter : IMultiValueConverter
{
  public object Convert(object[] values, Type targetType, object parameter,
      System.Globalization.CultureInfo culture)
  {
    DateTime time = (DateTime)values[0];
    string format = values[1].ToString();
    return time.ToString(format);
  }

  public object[] ConvertBack(object value, Type[] targetTypes, object parameter,
      System.Globalization.CultureInfo culture)
  {
    throw new NotImplementedException();
  }
}
Community
  • 1
  • 1
Yuval Peled
  • 4,988
  • 8
  • 30
  • 36
  • Okay so if we have the above XAML, which is the equivalent to what what your linked question solution, how do I get that to fit in with my converter - where 'MyTime' should be getting into the 'Value' param, and 'UserFormat' should be getting into the 'parameter' param. Remember the signature of a converter convert method is `public object Convert(object value, Type targetType, object parameter, CultureInfo culture)`. – Alain May 03 '12 at 12:14
  • Take a look at the first link I sent you. If you inherit from IMultiValueConverter you'll have an array of values. – Yuval Peled May 03 '12 at 22:46