Arithmetic operations in Xaml


One of the common hurdles (if you may call that) that I face while writing some xaml is performing simple arithmetic operations while binding. hmm… i am sure many have faced the same… The solution is writing an IValueConverter and you are set… For simple math like [ActualHeight+10] we can readily use the ArithmeticConverter code. This will allow operations like



    1   <Window.Resources>


    2     <local:ArithmeticConverter x:Key=arithConverter />


    3   </Window.Resources>


    4   <TextBlock Height={Binding ElementName=tb1, Path=ActualHeight,


    5      Converter={StaticResource AScript}, ConverterParameter=Int32.Parse(values[0])-100 } />


 


 


The code however will not do multiple arithmetic operations. I really didnt need a converter which did more than that. However, Douglas has written a converter which does exactly that and extends it further to multibinding. Now using his converter we can perform operations like the below in Xaml.


 



    1 <StackPanel.Resources>


    2   <local:JScriptConverter x:Key=JScript TrapExceptions=False />


    3 </StackPanel.Resources>


    4 <TextBlock Height={Binding ElementName=tb1, Path=ActualHeight,


    5     Converter={StaticResource JScript},


    6     ConverterParameter=Int32.Parse(values[0])/10 *100-110 } Background=Red/>


PS: both the converters are attached in a sample project.

Converter.zip

Comments (4)

  1. Aaron says:

    For the ArithmeticConverter, why is the "Int32.Parse(values[0])" necessary?

    The code only operates on the "-100" part.

  2. llester says:

    Aaron, you are right.. its not necessary 🙂