chrisspace
chrisspace

Reputation: 15

How I can hide an element when a switch is toggled?(in XAML)

I wish to hide the first two stacklayouts, when the switch for "Current" is toggled. Ty. Here is my code, but now the stacklayouts appear when the switch is toggled. I need the opposite result.

               <ViewCell>
                   <StackLayout  Orientation="Horizontal" HorizontalOptions="Fill"
                              IsVisible="{Binding Source={x:Reference switch}, Path=IsToggled}">
                        <Label  Text="Date From:" />
                        <DatePicker Date="{Binding SettingsView.DateFrom, Mode=TwoWay}" 
                                  HorizontalOptions="End"  TextColor="White" FontAttributes="Bold"/>
                    </StackLayout>
                </ViewCell>
                <ViewCell>
                    <StackLayout  Orientation="Horizontal" 
                                  IsVisible="{Binding Source={x:Reference switch}, Path=IsToggled}">
                        <Label Text="Date To:"/>                                    
                        <DatePicker Date="{Binding SettingsView.DateTo, Mode=TwoWay}"  TextColor="White" FontAttributes="Bold"/>
                    </StackLayout>
                </ViewCell>
                <ViewCell>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <Label Text="Current" Grid.Column="0" x:Name="label" />
                        <Switch x:Name="switch"  IsToggled="{Binding SettingsView.Today, Mode=TwoWay}" Grid.Column="1" />
                    </Grid>
                </ViewCell>

Upvotes: 0

Views: 97

Answers (1)

Lucas Zhang
Lucas Zhang

Reputation: 18861

There are many solutions which can implement it . For example you could use Converter

public class BoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var toggle = (bool)value;

        return !toggle;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
       return true;
    }
}

in xaml

<ContentPage.Resources>
        <ResourceDictionary>
            <local:BoolConverter  x:Key="BoolConverter" />
        </ResourceDictionary>
    </ContentPage.Resources>
IsVisible="{Binding Source={x:Reference switch}, Path=IsToggled, Converter={StaticResource BoolConverter}}"

Upvotes: 1

Related Questions