【问题标题】:Pass parameters to custom view from xaml将参数从 xaml 传递给自定义视图
【发布时间】:2018-04-17 16:45:12
【问题描述】:

在我的 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 属性?

【问题讨论】:

    标签: xamarin.forms


    【解决方案1】:

    您必须创建一个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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-27
      • 2011-11-10
      相关资源
      最近更新 更多