Betty Crokker
Betty Crokker

Reputation: 3341

Xamarin Forms XAML - create custom control that has no UI?

Let's say I want to define some data in my XAML which I then use in multiple places in that same XAML, something like this:

<custom:Definition Identifier="MyTemplate">
   <custom:Data Value="3" />
   <custom:Data Value="6" />
   <custom:Data Value="12" />
</custom:Definition>

<custom:Control Template="MyTemplate" />
<custom:Control Template="MyTemplate" />
<custom:Control Template="MyTemplate" />

So the "Template" object doesn't show up in the UI at all, it's just data. I was thinking I could define an object that derived from Element, like this:

[ContentProperty("Content")]
public class Definition : Element
{
    public static readonly BindableProperty ContentProperty = BindableProperty.Create(nameof(Content), typeof(List<object), typeof(Definition), null);
    public List<object> Content { get; set; }
    public string Identifier {get; set; }
}

But when I do this, XAML complains "No property, bindable property, or event found for 'Content', or mismatching type between value and property".

It doesn't matter what I put for the type of the 'Content' property, or what I put in my XAML inside the tags (even if the Definition tag has no children), I always get the same error message.

How can I add a non-UI element to a XAML?

Upvotes: 2

Views: 1452

Answers (1)

Diego Rafael Souza
Diego Rafael Souza

Reputation: 5313

Your bindable property shouldn't be set to the shown below?

[ContentProperty("Content")]
public class Definition : Element
{
    public static readonly BindableProperty ContentProperty = BindableProperty.Create(nameof(Content), typeof(List<object>), typeof(Definition), null);
    public List<object> Content 
    { 
        get { return (List<object>)GetValue(ContentProperty); } 
        set { SetValue(ContentProperty, value); }
    }
    public string Identifier {get; set; }

    public Definition()
    {
        Content = new List<object>();
    }
}

I like your purpose. It's very reusable for many applications.

The injection of your class would be like highlighted on the image:

Class injection on the Element's class hierarchy

Upvotes: 2

Related Questions