Link Search Menu Expand Document

Embedded C# Expressions in XML

  1. Embedded C# Expressions in XML
    1. Declaring Embedded Expression
    2. String in expressions
    3. AND operator and the ‘&’ symbol
    4. Multi-line expressions
    5. Common scenarios

Declaring Embedded Expression

You can embed C# expressions in property values in XML using the $ prefix:

<EmbeddedExpressionsExample ClickCount="t:int">
  <Group Orientation="Horizontal" Spacing="5"> 
    <Button Text="Click Me" Click="$ ++ClickCount" />
    <Label Text="$ Math.Pow({ClickCount}, 2).ToString()" />

The above example contains two embedded expressions:

  1. Button click handler that increases the click count:

    Click="$ ++ClickCount">

  2. Label text that presents the click count squared:

    Text="$ Math.Pow({ClickCount}, 2).ToString()"

    The above expression creates a transform binding that will update whenever ClickCount changes.

Note that in the expression you have access to all the local properties of the parent view as well as any other code in your project.

String in expressions

Strings in expressions are specified using single quotes:

<Label Text="$ 'hello world' " /> 

AND operator and the ‘&’ symbol

XML treats & as a special character, so you need to use &amp; to insert the symbol. Since the conditional logical AND operator (&&) is so common the framework translates the word AND to &&:

<Label Text="Text" IsActive="$ {ClickCount} > 0 AND {ClickCount} < 10" /> 

Which translates to the C# code:

IsActive = ClickCount > 0 && ClickCount < 10

You can also use the word OR instead of || although it’s not necessary as the symbols are allowed in XML.

Multi-line expressions

Multi-line expressions can be declared by inserting brackets into the expression. Start and end brackets are defined using two brackets:

<Label Text="$ {{ string test = 'hello'; return test; }}" /> 

Note that you need to use a return statement to return the result of the evaluation.

Common scenarios

  1. Switching views on/off based on conditions:

    <Region IsActive="$ {MyEnum} == MyEnum.Active"> 
  2. Invoking view actions:

    <MyView CloseClick="t:Action">
      <Button Text="Close" Click="$ CloseClick.Invoke()" />
  3. Invoking methods and passing list item data:

    <List Items="{fruit in @Fruits}" BackgroundColor="White">
        <Label Text="$ GetDisplayName({fruit})" />
        <Button Text="Delete" Click="$ Models.Fruits.Remove(fruit)" />
  4. Using view-switcher:

      <ViewSwitcher Id="MySwitcher">
        <Region Id="ViewA">
          <Button Text="Switch to B" Click="$ MySwitcher.SwitchTo(ViewB)" />
        <Region Id="ViewB">
          <Button Text="Switch to A" Click="$ MySwitcher.SwitchTo(ViewA)" />