Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin binding default value in xaml

I would to set my IsVisible property of an object in Xaml by default at false. But when I open the page, it is visible, then the binding variable is evaluated, and if it is false, becomes invisible. I want that it is not visible by default, and the if the binding variable is true, it should become visible. I've tried to insert a default value in my binding for IsVisible property of my object. I've tried FallbackValue = Hidden or FallbackValue = Collapsed and more, even for TargetNullValue, but it doesn't works. I obtain always a XamlParseException.

Can anyone help me please? Thanks.

Code (simplified):

 <Grid HorizontalOptions="FillAndExpand"
       IsVisible="{Binding Path=Info.IsVisible, Converter={StaticResource BooleanToStringConverter}, FallbackValue=Collapsed}"
like image 675
benjaminbutton Avatar asked Jul 11 '17 09:07

benjaminbutton


1 Answers

The default value for your object for IsVisible is always true. This is independent from the Binding. You could overwrite this value in the code behind file with something like this:

<Image x:Name="myImage" Aspect="AspectFit" WidthRequest="20" 
       HeightRequest="20" HorizontalOptions="End" VerticalOptions="End" 
       IsVisible="{Binding PropertyNameOfYourModel}" />
// Somewhere in the constructor
this.myImage.IsVisible = false;

// Here the binding is set at a later time
this.BindingContext = yourModelObject;
this.myImage.SetBinding(Image.IsVisibleProperty, "PropertyNameOfYourModel");

Another solution could be DataTrigger, but I haven't tested it yet:

<Label Text="{Binding MyObject.Text}" IsVisible="false">
    <Label.Triggers>
        <DataTrigger TargetType="Label" Binding="{Binding MyObject.Text, Converter={StaticResource NotEmptyToBoolConverter}}" Value="True">
            <Setter Property="IsVisible" Value="True" />
        </DataTrigger>
    </Label.Triggers>
</Label>

Source

If you can wait for Xamarin.Forms 3.2.0, than you will have the options FallbackValue and TargetNullValue available directly in the Xamarin Xaml.

like image 140
testing Avatar answered Oct 16 '22 18:10

testing