Welcome to MSDN Blogs Sign in | Join | Help

Lester's WPF blog


Simple, easy & beautiful

News

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.

Posted: Monday, November 13, 2006 4:09 PM by llester
Attachment(s): Converter.zip

Comments

Ford said:

# December 16, 2006 7:48 AM

Ford said:

# December 16, 2006 7:48 AM

Aaron said:

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

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

# December 29, 2006 2:36 PM

llester said:

Aaron, you are right.. its not necessary :)

# December 29, 2006 11:19 PM
New Comments to this post are disabled
Page view tracker