XAM335 Mobile application architecture

Exercise 3: Create a custom control

In this exercise, you'll define a custom control to create a drawing surface that can be consumed in your shared code.

To complete the exercise, you will need Visual Studio for Windows or macOS with the Xamarin development tools installed. You will also need either an emulator/simulator or a device to run the exercise on. Please see the setup page if you need help installing the Xamarin development environment.

Open the starter solution

Open the starter XFDraw solution from the Exercise 3 > Start folder in your copy of the cloned or downloaded course materials in either Visual Studio on Windows or Visual Studio for Mac.

If you're using Visual Studio on Windows, you'll see all of the platform or head projects: iOS, Android and Windows. If you're using macOS, the Windows projects will be disabled (grayed out).


Create a custom element

  1. In the XFDraw shared project, create a new class named SketchView that derives from View.
  2. Create a BindableProperty named InkColorProperty. Set the propertyName as "InkColor", the return type as Color and the declaring type as the new element - SketchView.
  3. Create Color property named InkColor for the bindable property. Call the GetValue and SetValue methods, passing in InkColorProperty, in the getter/setter.
class SketchView : View
{
    public static readonly BindableProperty InkColorProperty = BindableProperty.Create("InkColor", typeof(Color), typeof(SketchView), Color.Blue);

    public Color InkColor
    {
        get { return (Color)GetValue(InkColorProperty); }
        set { SetValue(InkColorProperty, value); }
    }
}

Consume the custom element

You'll add the custom element to your visual content page. However, you haven't yet added any platform-specific rendering code so the view will be blank.

  1. Open MainPage.xaml in the shared project.
  2. Add a SketchView to the mainLayout Grid. You can use the same xmlns you defined for the hyperlink label.
  3. Give it a name of sketchView so that you can reach the control in the code-behind.
  4. Set the HorizontalOptions and VerticalOptions to FillAndExpand.
  5. Set the InkColor property to a default color, the code below uses green.
<local:SketchView x:Name="sketchView" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" InkColor="Green" />

Exercise summary

In this exercise, you created a custom element in Xamarin.Forms and added a bindable property to the element.

You can view the completed solution in the Exercise 3 > Completed folder of your copy of the cloned or downloaded course materials.

Go Back