将参数从xaml

时间:2018-04-17 16:45:12

标签: xamarin.forms

在我的Xamarin.Forms应用程序中,我有一个自定义视图:

[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
    }
}

我在我的XAML中使用它:

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

如何从xaml将参数传递给views:Checkbox?有没有办法绑定到我的BackgroundColor属性?

1 个答案:

答案 0 :(得分:5)

您必须创建BindableProperty,因此您的BackgroundColor属性应如下所示:

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));

比你可以绑定它:

<StackLayout Orientation="Horizontal">
    <Label Text="My custom view:"/>
    <views:Checkbox BackgroundColor="{Binding CheckBoxBgColor}" />
</StackLayout>