How can I stop a Toggled Event on a switch from being fired as a page is loaded?

前端 未结 2 1477
悲&欢浪女
悲&欢浪女 2021-01-18 14:02

My application has a switch set up in XAML and backend C# code that responds to the toggle event


   

        
2条回答
  •  滥情空心
    2021-01-18 14:37

    With your code above the Switch shouldn't trigger the event on first start. It triggers only if you have bound your IsToggled property with your ViewModel! The reason for that is, that the Page is initialized first, the ViewModel toggles the Switch and then the event is getting fired.

    First solution would be to handle the IsToggled property and the Toggled event both from the code-behind (not recommended if you are mvvm-ing your code). Better solution would be to handle both from the ViewModel.

    The problem is, that the Switch Control doesn't have a Command property. You have to use a Behaviour to bind to a Command. Sharada Gururaj already posted a Link above with a good explanation.

    Here is the short Solution form Sharada Gururajs stackoverflow link: Xamarin Forms Switch Toggled event doesn't bind with viewmodel

    
    
        
        
        
    
    

    Further Informations:

    • https://blog.xamarin.com/turn-events-into-commands-with-behaviors/
    • https://forums.xamarin.com/discussion/64374/switch-with-istoggled-binding-is-throwing-toggled-event-on-init-when-bound-value-is-true

提交回复
热议问题