使用Xamarin中的Binding来转换子类值

时间:2018-03-21 14:23:08

标签: c# xaml xamarin cross-platform

我在c#中有一个具有沉闷结构的班级人员:

public class Address
{
    public string Street {get;set;}
    public string Complement {get;set;}
    public string Number {get;set;}
    public string City {get;set;}
    public string Estate {get;set;}
    public string Zip {get;set;}
}
//...
public class Person
{
    public string ID {get;set;}
    public string Name {get;set;}
    public string Email {get;set;}
    public Address Address {get;set;}
    public string Genre {get;set;}
    public Phones Phone {get;set;}
    public string Birtday {get;set;}
}

在我的XAML文件中,我有:

<Grid HorizontalOptions="FillAndExpand" Padding="10">
      <Grid.RowDefinitions>
      <!-- ... -->
      <Label Text="{Binding Name}"
            HorizontalOptions="StartAndExpand"
            Grid.Row="0" TextColor="Blue"
            FontAttributes="Bold" />
      <Label Text="{Binding Email}"
            HorizontalOptions="StartAndExpand"
            Grid.Row="1" TextColor="Orange"
            FontAttributes="Bold" />
      <!-- so, how I can fill this label with all values in address class referenced in person class -->
      <Label Text="{Binding Address.Street + Address.Complement +", " + Address.Number + " - " + Address.City + "..."}"
            HorizontalOptions="StartAndExpand"
            Grid.Row="2" TextColor="Gray"
            FontAttributes="Bold" />
      <!-- ... -->
</Grid>

我是Xamarin和c#的菜鸟,有人可以帮助我为一个人在标签上直接绑定其部分投下完整的地址吗?
可以像我在我的注释代码中一样进行采样吗?

提前致谢

1 个答案:

答案 0 :(得分:1)

你不能在这样的绑定中将多个属性组合在一起。

最简单的方法是向Address

添加辅助属性
public string DisplayAddress {
  get {
    return Street + Complement +", " + Number + " - " + City + "..."; 
  }
}

然后绑定到

<Label Text="{Binding Address.DisplayAddress}"
        HorizontalOptions="StartAndExpand"
        Grid.Row="2" TextColor="Gray"
        FontAttributes="Bold" />