Steve
Steve

Reputation: 21

How can I create a custom Xamarin.Forms component that can be creating through xaml?

My apologies if this question has already been answered. I'd like to create a tab component with some specific behaviors based on Xamarin.Forms where the tab definition xaml is something similar to:

<Tab OnTabChange="Some_Event_Handler">
<Tabs>
<Tab Text="xxx" />
<Tab Text="yyy" />
</Tab>
</Tab>

Are there any resources available that use custom xaml that I can review?

Any insight is greatly appreciated.

Upvotes: 0

Views: 1905

Answers (1)

Jesse Liberty
Jesse Liberty

Reputation: 1414

The easiest way is to create a custom renderer. And the easiest way to do that is to extend an existing element and give it new capabilities.

The first step is to create the element. Inside the class create a static readonly BindableProperty and a non-static property which uses GetValue and SetValue. That will support data binding.

Each platform will need to know how to render your new control, so add a class such as MyLabelRenderer.cs. In that file you will want to override the methods that might need to render your control.

public class MyLabelRenderer : LabelRenderer
{
    protected override void OnElementChanged (
         ElementChangedEventArgs<Label> e)
    {
        base.OnElementChanged (e);
        MyLabel el = (MyLabel)this.Element;
        // custom stuff here
    }
}

You then declare a local namespace and can use your custom object

<local:myLabel  ... >

For a detailed walk-through see http://jliberty.me/customRenderer

Hope that helps

-jesse

Upvotes: 1

Related Questions