Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a If Else condition with xaml binding

I'm trying to create a XAML UI based on the condition.

<StackLayout Orientation="Horizontal">
              <!--IF WorkEmailAddress != NULL && WorkEmailAddrress != ""-->
              <!-- BEGIN IF -->
              <Label Text="{Binding WorkEmailAddress}" Style="{StaticResource labelListItem}"></Label>
              <Image HeightRequest="16" HorizontalOptions="End" VerticalOptions="Center" Source="arrow.png" Margin="0,0,15,0"></Image>
              <!-- END IF -->
              <!-- ELSE -->
              <Label Text="Add new email" Style="{StaticResource labelLinkItem}">
            </StackLayout>

Could one please let me know how to add a IF ELSE condition with in the XAML to dynamically create a UI based on the value returned from the backend.

like image 325
Aryan M Avatar asked Oct 30 '18 00:10

Aryan M


1 Answers

You can't do this completely in XAML. Probably the best way to go is to add a bool property to your view model named HasWorkEmailAddress (I'm assuming you have one, and that's where WorkEmailAddress lives) which returns true if there's a non-null, non-empty value for WorkEmailAddress.

You can then bind the first label and Image's IsVisible property to this bool.

You can also create an InverseBooleanConverter, which will implement IValueConverter. The Convert method will simply take a bool and negate it, and return that value. Bind your second labels' IsVisible to the same bool, but specify the InverseBooleanConverter as the binding's Converter. It will then show only if the HasWorkEmailAddress returns false. The labels binding will look like this:

<Label IsVisible="{Binding HasWorkEmailAddress, Converter={StaticResource InverseBooleanConverter}}" />

If you don't want to write your own converter, one exists in the FreshEssentials Nuget package.

One last thing; if its possible for WorkEmailAddress to change while the page is being shown, you'll need to make sure you raise a PropertyChanged event for the HasWorkEmailAddress property, or your view will not change appropriately.

like image 117
Andy Avatar answered Nov 13 '22 06:11

Andy