Computer Magic Logo
Call a method

Tuesday, April 12, 2016

Published by Aristotelis Pitaridis

In order to make the property assignment dynamic in XAML we can use methods in order to set the value of a property. In XAML we can call only methods which return objects or values of the same type that the property we try to assign have. The methods that we call must be public and static. Let's see an example.

<Label x:Name="MyLabel" Text="Hello World!">
  <Label.TextColor>
     <Color x:FactoryMethod="FromRgb">                     
       <x:Arguments>                         
         <x:Int32>255</x:Int32>                         
         <x:Int32>128</x:Int32>  
         <x:Int32>196</x:Int32>                     
      </x:Arguments>                 
    </Color>   
  </Label.TextColor>
</Label>

Inside the Label control we created a Label.TextColor element which informs XAML that we want to define the property TextColor of a Label. In this element we create a new element which informs XAML that it is going to be of type Color and we use the x:FactoryMethod in order to define the method that we want to call in order to get the Color object. In the Color element we create a new child which informs XAML that the method has some parameters. For each parameter we create an element in order to define the type and value of the parameter.

In XAML we use the .NET types instead of the C# types. 

  • x:Object
  • x:Boolean
  • x:Byte
  • x:Int16
  • x:Int32
  • x:Int64
  • x:Single
  • x:Double
  • x:Decimal
  • x:Char
  • x:String
  • x:TimeSpan
  • x:Array
  • x:DateTime (supported by Xamarin.Forms but not the XAML 2009 specification)