无法将对象的属性绑定到自定义控件

时间:2019-04-11 14:37:25

标签: c# data-binding xamarin.forms

我有一个绑定到视图模型的内容页面。

在视图模型中,我新建一个地址并为其提供一些数据

Address = new Address
{
     UserId = Guid.NewGuid(),
     PrimaryAddress = true,
     Postcode = "G23 5HU",
     Street = "Smith Street",
     City = "Large City",
     PhoneNumber = "115151"
};

我在内容页面上也有一个AddressInfo控件,就像这样

 <controls:AddressInfo Address="{Binding Address}"></controls:AddressInfo>

这是控制权本身

public partial class AddressInfo : ContentView
{
    public static readonly BindableProperty AddressProperty =
        BindableProperty.Create(nameof(Address), typeof(Address), typeof(AddressInfo), null);

    public Address Address
    {
        get { return (Address)GetValue(AddressProperty); }
        set { SetValue(AddressProperty, value); }
    }

    public AddressInfo()
    {
        InitializeComponent();
        Street.SetBinding(Label.TextProperty, new Binding(nameof(Address.Street), source: this));
        City.SetBinding(Label.TextProperty, new Binding(nameof(Address), source: this));
        PhoneNumber.SetBinding(Label.TextProperty, new Binding(nameof(Address), source: this));
        PostCode.SetBinding(Label.TextProperty, new Binding(nameof(Address), source: this));
    }

这是控件XAML

<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="TyreKlicker.XF.Core.Controls.AddressInfo">
<ContentView.Content>

    <StackLayout>
        <Label
                x:Name="Street"
                Text="{Binding Address.Street}" />
        <Label
                x:Name="City"
                Text="{Binding Address.City}" />
        <Label  Text="Hardcoded Text" ></Label>
        <Label
                x:Name="PostCode"
                Text="{Binding Address.Postcode}" />
        <Label
                x:Name="PhoneNumber"
                Text="{Binding Address.PhoneNumber}" />

        <Label x:Name="CardHeader"
                   Text="{Binding Header}"
                   TextColor="{StaticResource PrimaryDark}"
                   FontSize="Large" Margin="10,0,0,0" />

        <Button Clicked="Button_OnClicked"></Button>
    </StackLayout>
</ContentView.Content>

当我运行它时,我希望可以看到“地址”属性,但是除了硬编码文本外,其全部为空白

Picture of the app running

如果我停止了Button_OnClicked事件,我向控件中添加了一个按钮以帮助调试,我可以看到Address的属性并且它具有正确的数据,但是它只是不在列表中显示我在做什么错误吗?

Address properties

1 个答案:

答案 0 :(得分:0)

由于杰森(Jason)的提示,我从AddressInfo构造函数中删除了以下几行,并且中提琴起作用了

        //Street.SetBinding(Label.TextProperty, new Binding(nameof(Address.Street), source: this));
        //City.SetBinding(Label.TextProperty, new Binding(nameof(Address), source: this));
        //PhoneNumber.SetBinding(Label.TextProperty, new Binding(nameof(Address), source: this));
        //PostCode.SetBinding(Label.TextProperty, new Binding(nameof(Address), source: this));

感谢您的帮助!