[Xamarin] How to implement the FallBackValue/TargetNullValue in Xamarin.Forms’ Bindings ?

February 17th, 2016 | Posted by Tom in .NET | Article | Xamarin | Read: 4,240

Today, I’ve worked on a Xamarin.Forms application and I wanted to use the following code:

<Label FontAttributes="Bold"
       TextColor="Gray" Text="{Binding CurrentUser.FullName, FallBackValue=Username}">

Looks pretty simple for anyone working with XAML: if my CurrentUser.FullName is not available, I want to put the string “Username” in the Label.

Unfortunately, the previous code does not work because FallBackValue (and TargetNullValue) are not available on the Binding object (this appears to be a known issue to the Xamarin team for a long time now: https://bugzilla.xamarin.com/show_bug.cgi?id=22720).

So, to workaround the problem, I’ve simply used a Trigger:

<Label FontAttributes="Bold"
       TextColor="Gray" Text="{Binding CurrentUser.FullName}">
    <DataTrigger TargetType="Label" Binding="{Binding CurrentUser.FullName}" Value=" ">
      <Setter Property="Text">Username</Setter>

As we’are using a Binding in the Binding property, we are free to use any converter needed to compute the value of our property. This is a bit more verbose but, at least, it works fine!


Happy coding!

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

Add Comment Register

Leave a Reply