简体   繁体   English

Xamarin Forms 中的条件文本

[英]Conditional text in Xamarin Forms

How do I conditionally render a particular text in Xamarin Forms 5?如何有条件地呈现 Xamarin Forms 5 中的特定文本?

For example, I get some data from my API backend for a vendor and there may be an address in the database for this vendor or not.例如,我从供应商的 API 后端获取了一些数据,数据库中可能有或没有该供应商的地址。

If I do have vendor's address, I'd like to display it and if I don't have an address, I'd like to display something like "n/a".如果我有供应商的地址,我想显示它,如果我没有地址,我想显示类似“n/a”的内容。

Is there a way to handle this in the XAML page or do I have to handle it in code behind?有没有办法在 XAML 页面中处理这个问题,还是我必须在代码后面处理它?

UPDATE: Here's what the XAML page for the phone numbers ListView looks like:更新:电话号码ListView的 XAML 页面如下所示:

<Grid Grid.Row="1" Grid.Column="0" RowDefinitions="150, *" ColumnDefinitions="250, 250">
   <StackLayout
      Grid.Row="0"
      Grid.Column="0"
      Padding="10">
      <ListView
         BackgroundColor="Transparent"
         SeparatorVisibility="None"
         ItemsSource="{Binding Contact.PhoneNumbers, TargetNullValue='n/a'}">
         <ListView.Header>
            <StackLayout>
               <Label Text="Phone Number(s)"
                  FontAttributes="Bold"/>
            </StackLayout>
         </ListView.Header>
         <ListView.ItemTemplate>
            <DataTemplate>
                <TextCell Text="{Binding PhoneNumberDisplay}" />
            </DataTemplate>
         </ListView.ItemTemplate>
      </ListView>
   </StackLayout>
</Grid>

You can use xaml binding with TargetNullValue您可以使用 xaml 与TargetNullValue绑定

<Label Text="{Binding Location, TargetNullValue='n/a'}"/>

If you don't have an address your API or your code should set Location to null in order for TargetNullValue to work.如果您没有地址 API 或您的代码应将Location设置为 null 以使 TargetNullValue 起作用。

Update (reply to this comment ).更新(回复此评论)。

Use TargetNullValue in the bindings inside ItemTemplate (applies to each single element) and not on itemsource binding:在 ItemTemplate 内的绑定中使用TargetNullValue (适用于每个单个元素)而不是在 itemsource 绑定上:

<Grid Grid.Row="1" Grid.Column="0" RowDefinitions="150, *" ColumnDefinitions="250, 250">
   <StackLayout
      Grid.Row="0"
      Grid.Column="0"
      Padding="10">
      <ListView
         BackgroundColor="Transparent"
         SeparatorVisibility="None"
         ItemsSource="{Binding Contact.PhoneNumbers}">
         <ListView.Header>
            <StackLayout>
               <Label Text="Phone Number(s)"
                  FontAttributes="Bold"/>
            </StackLayout>
         </ListView.Header>
         <ListView.ItemTemplate>
            <DataTemplate>
                <TextCell Text="{Binding PhoneNumberDisplay, TargetNullValue='n/a'}" />
            </DataTemplate>
         </ListView.ItemTemplate>
      </ListView>
   </StackLayout>
</Grid>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM