简体   繁体   中英

Conditional text in Xamarin Forms

How do I conditionally render a particular text in 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.

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".

Is there a way to handle this in the XAML page or do I have to handle it in code behind?

UPDATE: Here's what the XAML page for the phone numbers ListView looks like:

<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

<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.

Update (reply to this comment ).

Use TargetNullValue in the bindings inside ItemTemplate (applies to each single element) and not on itemsource binding:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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