Lester's WPF\SL Blog

Simple, Easy & Beautiful

Arithmetic operations in Xaml

Arithmetic operations in Xaml

Rate This
  • Comments 4

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.

Attachment: Converter.zip
Page 1 of 1 (4 items)