0
votes

I am new to Xamarin.Forms. My project is a cross platform PCL. Single Page. Built using VS 2017. This question pertains to the iOS platform.

Background: App layout has 13 images all with the IsVisible=False. Each image has a toggle switch.

Objective: To have the user be able to control the image visibility through the toggle switch. When the switch is toggled the image will become visible.

Code sample below. Any insight would be greatly appreciated. Thank you.

XAML

<AbsoluteLayout>
    <Image x:Name="Sheep_Image" Source="1-Sheep.png" Aspect="AspectFit" AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds=".15,.87,.5,.1" IsVisible="False"/>
    <Switch x:Name="Switch" Toggled="Switch_Toggled"/>
</AbsoluteLayout>

xaml.cs

private void Switch_Toggled(object sender, ToggledEventArgs e){
    var toggle = sender as ToggleSwitch;
    Sheep_Image.IsVisible = toggle.IsOn;
}
4

4 Answers

0
votes

The property for Toggle is called "IsToggled"

0
votes

You need to subscribe an event handler to each toggle:

        void Handle_Toggled(object sender, Xamarin.Forms.ToggledEventArgs e)
        {
            Sheep_Image.IsVisible = e.Value;
        }

In XAML, you need this:

<Switch Toggled="Handle_Toggled" />
0
votes

This should work too:

<Image x:Name="Image"></Image>
<Switch IsToggled="{Binding Source={x:Reference Image}, Path=IsVisible, Mode=TwoWay}" HorizontalOptions="Start"></Switch>
0
votes

As @Dbl,@lowry0031, @BraveHeart said, I just make a summary and provide more details.

Solution 1 : Event Handle

private void Switch_Toggled(object sender, ToggledEventArgs e){
    Sheep_Image.IsVisible = (sender as Switch).IsToggled;
    //Or 
   //Sheep_Image.IsVisible = e.Value; 
}

Solution 2 : Binding

<Image x:Name="Sheep_Image" Source="Icon-Small.png" Aspect="AspectFit" AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds=".15,.87,.5,.1" IsVisible="False"/>
<Switch x:Name="Switch" IsToggled="{Binding Source={x:Reference Sheep_Image}, Path=IsVisible, Mode=TwoWay}"/>

PS: Make sure the image is available in your Resource folder.

enter image description here

Test

enter image description here