簡體   English   中英

無法將對象的屬性綁定到自定義控件

[英]Unable to bind properties of an object to a custom control

我有一個綁定到視圖模型的內容頁面。

在視圖模型中,我新建一個地址並為其提供一些數據

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>

當我運行它時,我希望可以看到Address屬性,但是除了Hardcoded Text之外,其全部為空白

正在運行的應用程序的圖片

我在控件上添加了一個按鈕,以幫助調試,如果我停止了Button_OnClicked事件,我可以看到該地址的屬性,並且它具有正確的數據,但是它只是沒有在列表中顯示,這是我做錯了什么?

地址屬性

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

謝謝您的幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM