Xamarin Community Toolkit MathExpressionConverter

Pre-release API.

The MathExpressionConverteris a converter that allows users to calculate an expression at runtime from supplied arguments:

  • x or x0 — The first argument
  • x1 — The second argument
  • ...
  • xN-1 — The N argument

Warning

Avoid negative operations, constants or variables such as "-cos(30)", "-x" or "-pi", which will return an error. Instead, use multiplication by -1.

Syntax

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
             x:Class="MyLittleApp.MainPage">
    <ContentPage.Resources>
         <ResourceDictionary>
             <xct:MathExpressionConverter x:Key="MathExpressionConverter" />
             <xct:MultiMathExpressionConverter x:Key="MultiMathExpressionConverter" />
         </ResourceDictionary>
    </ContentPage.Resources>

    <StackLayout>

        <Frame
           x:Name="CalculatedFrame"
           HeightRequest="120"
           CornerRadius="{Binding Source={x:Reference CalculatedFrame}, Path=HeightRequest, Converter={StaticResource MathExpressionConverter}, ConverterParameter='x/2'}">

        <Label TextColor="Black">
            <Label.Text>
                <MultiBinding Converter="{StaticResource MultiMathExpressionConverter}"
                              ConverterParameter="x0 * x1"
                              StringFormat="The area of Frame = {0}">
                    <Binding Path="{Binding Source={x:Reference CalculatedFrame}, Path=HeightRequest}" />
                    <Binding Path="{Binding Source={x:Reference CalculatedFrame}, Path=WidthRequest}" />
                </MultiBinding>
            </Label.Text>
        </Label>

    </StackLayout>
</ContentPage>

Operations

Operation Example Equivalent
+ x + 1
- x - 2
* x * -3
/ x / 4
^ x ^ 5 Math.Pow
abs abs(x) Math.Abs
acos acos(x) Math.Acos
asin asin(x) Math.Asin
atan atan(x) Math.Atan
atan2 atan2(x, 10) Math.Atan2
ceiling ceiling(x) Math.Ceiling
cos cos(x) Math.Cos
cosh cosh(x) Math.Cosh
exp exp(x) Math.Exp
floor floor(x) Math.Floor
ieeeremainder ieeeremainder(x, 16) Math.IEEERemainder
log log(x, 17) Math.Log
max max(x, 18) Math.Max
min min(x, 19) Math.Min
pow round(x, 2) Math.Pow
round round(x, 1) Math.Round
sign sign(x) Math.Sign
sin sin(x) Math.Sin
sinh sinh(x) Math.Sinh
sqrt sqrt(x) Math.Sqrt
tan tan(x) Math.Tan
tanh tanh(x) Math.Tanh
truncate truncate(x) Math.Truncate

Constants

Constant Equivalent
e Math.E
pi Math.PI

Sample

MathExpressionConverter sample page Source

You can see this in action in the Xamarin Community Toolkit Sample App.

API