5

Xamarin.Forms: Use converters with binding objects which can have null as value.

 2 years ago
source link: https://www.banditoth.hu/2021/11/12/xamarin-forms-use-converters-with-binding-objects-which-can-have-null/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Xamarin.Forms: Use converters with binding objects which can have null as value.

November 12, 2021 by banditoth

You have a converter, which should return a specific value, even if the binded object is null.

Converters does not get executed, when the binded value is null. But here is a solution, how to handle this situations.

Define an example converter

In this case we will use an Int value to bool value converter.

public class IsIntGreaterThanConverter : IValueConverter, IMarkupExtension
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is int bindedValue && parameter is int targetValue)
{
return bindedValue > targetValue;
}
else
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
public object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}

This code returns true, if the binded value is greater than the value provided as a converter parameter.

It can be used with the following code snippet in XAML:

<Label Text="The value is greater than 0">
<Label.IsVisible>
<Binding Path="Object.IntValue"
Converter="{app1:IsIntGreaterThanConverter}">
<Binding.ConverterParameter>
<x:Int32>0</x:Int32>
</Binding.ConverterParameter>
</Binding>
</Label.IsVisible>
</Label>

But what happends, when the ‘Object’ is null? Well the converter does not get executed. And since View’s default value of the IsVisible bindable property is true, then the label will be visible, even if the Object is null.

How to handle null scenarios?

Bindings have a property called FallbackValue. Give a value to the fallbackvalue property in order to override the default value, like this:

<Label Text="The value is greater than 0">
<Label.IsVisible>
<Binding Path="Object.IntValue"
FallbackValue="False"
Converter="{app1:IsIntGreaterThanConverter}">
<Binding.ConverterParameter>
<x:Int32>0</x:Int32>
</Binding.ConverterParameter>
</Binding>
</Label.IsVisible>
</Label>

This should return false even if the binded obejct is null. 🙂


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK