wpf Usage converters with ConverterParameter


Example

Show how to create simple converter and use ConverterParameter to pass parameter to converter. Multiply value by coefficient passed in ConverterParameter.

public class MultiplyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return 0;

        if (parameter == null)
            parameter = 1;

        double number;
        double coefficient;

        if (double.TryParse(value.ToString(), out number) && double.TryParse(parameter.ToString(), out coefficient))
        {
            return number * coefficient;
        }

        return 0;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

Using the converter

  1. Define namespace
xmlns:converters="clr-namespace:MyProject.Converters;assembly=MyProject"
  1. Define Resource
<converters:MultiplyConverter x:Key="MultiplyConverter"/>
  1. Use it in binding
<StackPanel Orientation="Vertical">
    <TextBox x:Name="TextBox" />
    <TextBlock Text="{Binding Path=Text, 
                              ElementName=TextBox, 
                              Converter={StaticResource MultiplyConverter},
                              ConverterParameter=10}"/>
</StackPanel>