Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameters to custom view from xaml

In my Xamarin.Forms application, I have a custom view:

[Xamarin.Forms.ContentProperty("Content")]
public class Checkbox : ContentView
{
    Label lbl = new Label() { Text = "\u2610" }; // \u2610 Uni code will show empty box
    Label lbl1 = new Label() { Text = "Has arrived" };

    public string BackgroundColor { get; set; }

    public Checkbox()
    {
        TapGestureRecognizer t = new TapGestureRecognizer();

        t.Tapped += OnTapped;

        StackLayout stackLayout = new StackLayout()
        {
            Orientation = StackOrientation.Horizontal,
            HorizontalOptions = LayoutOptions.StartAndExpand,
            Children = {lbl,lbl1}
        };

        stackLayout.GestureRecognizers.Add(t);

        Content = stackLayout;
    }

    public void OnTapped(object sender, EventArgs args)
    {
        lbl.Text = lbl.Text == "\u2611" ? "\u2610" : "\u2611"; // \u2611 Uni code will show checked Box
    }
}

And I use it in my XAML as such:

<StackLayout Orientation="Horizontal">
    <Label Text="My custom view:"/>
    <views:Checkbox />
</StackLayout>

How can I pass parameters to views:Checkbox from the xaml? Is there a way to bind to my BackgroundColor property?

like image 418
Drake Avatar asked Apr 17 '18 16:04

Drake


1 Answers

You have to create a BindableProperty, so your BackgroundColor property should look like:

public string BackgroundColor
{
    get { return (string)GetValue(BackgroundColorProperty); }
    set { SetValue(BackgroundColorProperty, value); }
}

public static readonly BindableProperty BackgroundColorProperty =
    BindableProperty.Create(nameof(BackgroundColor), typeof(string), typeof(Checkbox));

Than you could bind to it:

<StackLayout Orientation="Horizontal">
    <Label Text="My custom view:"/>
    <views:Checkbox BackgroundColor="{Binding CheckBoxBgColor}" />
</StackLayout>
like image 186
EvZ Avatar answered Oct 15 '22 14:10

EvZ