Computer Magic Logo
Constructor with arguments

Tuesday, April 12, 2016

Published by Aristotelis Pitaridis

Most of the times we set the value of a property using just a string value. For example if we want to set the text color of a label to red, we will just set the property TextColor to be equal to Red. But how can we create a new custom color. In order to do it in xamarin we will have to use the Color constructor and give the three values which define the custom color that we want to use. Is it possible to do it inside our Xamarin code? Let's see see how to do it using Xamarin.

<Label x:Name="MyLabel" Text="Hello World!">
  <Label.TextColor>
    <Color>
      <x:Arguments>
        <x:Double>1</x:Double>
        <x:Double>0.5</x:Double>
        <x:Double>0.7</x:Double>
      </x:Arguments>
    </Color>
  </Label.TextColor>
</Label>

As we can see, instead of typing in-line the name of a color, we create a child element inside the Label tag. We define that this element is going to be the TextColor property of a Label and inside this element we create a Color element. We inform the XAML that the Color element will take some parameters by using the x:Arguments element and inside this element we define the parameters. The constructor of the Color class that we will use takes three parameters of type Double. For each parameter we define the type and the value.

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)