Alain
Alain

Reputation: 27220

How to make Converters with bindable ConverterParameters?

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?

Upvotes: 1

Views: 2724

Answers (1)

Yuval Peled
Yuval Peled

Reputation: 5038

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();
  }
}

Upvotes: 7

Related Questions