Home > Mobile >  Conditional text in Xamarin Forms
Conditional text in Xamarin Forms

Time:03-09

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>

CodePudding user response:

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