WPF DataBinding with simple arithmetic operation?

I use a MathConverterthat I created to do all simple arithmatic operations with. The code for the converter is here and it can be used like this:

<TextBox Canvas.Top="{Binding SomeValue, 
             Converter={StaticResource MathConverter},
             ConverterParameter=@VALUE+5}" />

You can even use it with more advanced arithmatic operations such as

Width="{Binding ElementName=RootWindow, Path=ActualWidth,
                Converter={StaticResource MathConverter},
                ConverterParameter=((@VALUE-200)*.3)}"

I believe you can do this with a value converter. Here is a blog entry that addresses passing a parameter to the value converter in the xaml. And this blog gives some details of implementing a value converter.


Using a value converter is a good solution to the problem as it allows you to modify the source value as it's being bound to the UI.

I've used the following in a couple of places.

public class AddValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        object result = value;
        int parameterValue;

        if (value != null && targetType == typeof(Int32) && 
            int.TryParse((string)parameter, 
            NumberStyles.Integer, culture, out parameterValue))
        {
            result = (int)value + (int)parameterValue;
        }

        return result;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Example

 <Setter Property="Grid.ColumnSpan"
         Value="{Binding 
                   Path=ColumnDefinitions.Count,
                   RelativeSource={RelativeSource AncestorType=Grid},
                   Converter={StaticResource addValueConverter},
                   ConverterParameter=1}"
  />