如何在 Xamarin.Forms 中连接字符串?

问题描述:

我希望我的两个字符串只显示在一行上.它是否可能像这样显示:

I want my two strings to be diplayed on just a single line. Is it possible for it to appear like this:

咖喱斯蒂芬

使用此代码

Text="{绑定 EMP_LAST_NAME + EMP_FIRST_NAME}" ???

我目前有这个代码.非常感谢.

I currently have this code. Thanks a lot.

<ListView ItemsSource="{Binding EmployeesList}"
        HasUnevenRows="True">
<ListView.ItemTemplate>
  <DataTemplate>
    <ViewCell>
      <Grid Padding="10" RowSpacing="10" ColumnSpacing="5">
        <Grid.RowDefinitions>
          <RowDefinition Height="Auto"/>
          <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="Auto"/>
          <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <controls:CircleImage Source="icon.png"
               HeightRequest="66"
               HorizontalOptions="CenterAndExpand"
               Aspect="AspectFill"
               WidthRequest="66"
               Grid.RowSpan="2"
               />

        <Label Grid.Column="1"
              Grid.Row="1"
              Text="{Binding EMP_LAST_NAME}"
               TextColor="White"
               FontSize="18"
               Opacity="0.6"/>

        <Label Grid.Column="1"
              Grid.Row="1"
              Text="{Binding EMP_FIRST_NAME}"
               TextColor="White"
               FontSize="18"
               Opacity="0.6"/>



      </Grid>
    </ViewCell>
  </DataTemplate>
</ListView.ItemTemplate>

您不能绑定到 View Element 上的多个属性.

You can't bind to multiple properties on a View Element.

在这种情况下,您应该创建一个新的属性来执行您想要的格式并将其绑定到 View.

In this case you should create a new property which does the format you want and bind it to the View.

示例:

public class EmployeeViewModel
{
    public string FirstName { get; set; }    
    public string LastName { get; set; }    
    public string FullName => $"{FirstName} {LastName}";
}

然后在 XAML 中:

<Label Text="{Binding FullName}"/>

另一种方法:

正如评论中所建议的,我们还可以在 Label 中使用 FormattedText 属性:

As suggested in the comments we can also use FormattedText property in a Label:

<Label.FormattedText>
   <FormattedString>
     <Span Text="{Binding FirstName}" />
     <Span Text="{Binding LastName}"/>
   </FormattedString>
</Label.FormattedText>