I am running into a scenario where I am binding to a property from my viewmodel in my xaml view where the VM property might be null. This causes my view not to load because I believe that I am getting a NullReferenceException.
VM:
public class PersonDetailViewModel : ViewModelBase
{
public Person CurrentPerson
{
get => currentPerson;
set => SetProperty(ref currentPerson, value);
}
private Person currentPerson;
public bool IsBobsFriendsVisible => FriendNamedBob?.Friends?.Count > 0;
public Person FriendNamedBob => CurrentPerson?.Friends?.FirstOrDefault(x => x.Name == "Bob");
public PersonDetailViewModel()
{
CurrentPerson = new Person()
{
Name = "Henry",
Friends = new List<Person>() { new Person() { Name = "Rachel" } }
};
}
}
XAML:
<ContentPage>
<ContantPage.Content>
<StackLayout>
<Label Text="Bob's Friends Count:" IsVisible="{Binding IsBobsFriendsVisible}" />
<Label Text="{Binding FriendNamedBob.Friends.Count}" IsVisible="{Binding IsBobsFriendsVisible}" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
This line is causing the issue obviously since FriendNamedBob
is null:
<Label Text="{Binding FriendNamedBob.Friends.Count}" IsVisible="{Binding IsBobsFriendsVisible}" />
What is the recommended technique for dealing with this scenario? Is this a sign of bad design?
Update:
It seems that a FallBackValue
of sorts (TargetNullValue
included) is not yet supported in Xamarin.Forms https://github.com/xamarin/Xamarin.Forms/issues/1803 also the DataTrigger does not work when checking for null https://bugzilla.xamarin.com/show_bug.cgi?id=57863
Thus, this is not a duplicate (yet) -- what are people currently doing in this situation?