Forum Xamarin.Forms
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

Binding a switch

StevenSajjaStevenSajja USMember, University
edited September 2015 in Xamarin.Forms

Hey guys,

I am trying to SetBinding to a switch in Code - behind (not XAML) but I have not been successful.

homePhoneSwitch.Toggled += (object sender, ToggledEventArgs e) => {
            ViewModel.Settings.HomePhone = e.Value; 

Doing the step above works fine but I have so many switches in my views and this is not an ideal solution.

I have attempted to use SetBinding like this:

        homePhoneSwitch.SetBinding (Switch.IsToggledProperty, new Binding ("Settings.HomePhone"));      
&&                     homePhoneSwitch.SetBinding (Switch.IsToggledProperty, new Binding ("ViewModel.Settings.HomePhone"));
&&          homePhoneSwitch.SetBinding (Switch.IsToggledProperty,  "Settings.HomePhone");

None of the above has worked for me. Is there something I am missing?
This is frustrating as on XAML its fairly straightforward but in the code-behind doesn't seem to work.

Any help is highly appreciated.


  • adamkempadamkemp USInsider, Developer Group Leader mod

    Can you make a small test project that shows what you're trying to do and attach it here? The important piece of information is probably in the view model, but it helps having a full working project to look at.

  • Andrew_RobertsAndrew_Roberts USMember ✭✭

    Perhaps you need to set the BindingContext on the Switch to whatever object your "Settings" property belongs to?

  • BonKeriBonKeri DEMember ✭✭

    do you have now a solution for this? thanks

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    @BonKeri which is the problem? post some code...

  • BonKeriBonKeri DEMember ✭✭
    edited November 2017

    The problem is when i open a page which includes the Switch Control in XAML the page is to slow, i get it work in XAML but im interessted to do this from Code behind:

     <Switch x:Name="ewSwitch"/>
     <StackLayout x:Name="kWohlbefindenStack" IsVisible="{Binding Source={x:Reference kwSwitch}, Path=IsToggled}" /> 
    How to add the Switch from Code behind with that binding and why is it so slow in XAML?


  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    Are you sure in Swtich the problem?

Sign In or Register to comment.