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
- In the XFDraw shared project, create a new class named SketchView that derives from View.
-
Create a
BindableProperty
named InkColorProperty. Set the propertyName as "InkColor", the return type asColor
and the declaring type as the new element - SketchView. -
Create Color property named InkColor for the bindable property. Call the
GetValue
andSetValue
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.
- Open MainPage.xaml in the shared project.
- Add a SketchView to the mainLayout Grid. You can use the same xmlns you defined for the hyperlink label.
- Give it a name of sketchView so that you can reach the control in the code-behind.
-
Set the
HorizontalOptions
andVerticalOptions
toFillAndExpand
. -
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.