If there are only two subviews in the ViewCell
, I would access the control in this way:
First, I created a custom mySwitch and add a bindable property name
to it, you can use this name later to figure out which switch
you are toggling:
public class mySwitch : Switch
{
public static readonly BindableProperty nameProperty =
BindableProperty.Create("name", typeof(string), typeof(MainPage), null);
public string name
{
get { return (string)GetValue(nameProperty); }
set { SetValue(nameProperty, value); }
}
}
In xaml, here I write a listView as an example and I set binding to the name of switch as the same as text of label:
<ContentPage.Content>
<ListView>
<ListView.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>wifi</x:String>
<x:String>sound</x:String>
</x:Array>
</ListView.ItemsSource>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout BackgroundColor="#eee" Orientation="Vertical">
<StackLayout Orientation="Horizontal">
<Label Text="{Binding .}" TextColor="#f35e20" />
<local:mySwitch name="{Binding .}" HorizontalOptions="End" OnColor="LightSeaGreen" IsToggled="{Binding IsVisible}" Toggled="Switch_Toggled" />
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage.Content>
in code behind, you can access the switch by sender
, access the ParentStackLayout by sender.parent
, and access the label by (Label)ParentStackLayout.Children[0]
, then use the name of switch to distinguish switch and change the text of corresponding
configLabel:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void Switch_Toggled(object sender, ToggledEventArgs e)
{
var Switch_ToggledHandler = (mySwitch)sender;
StackLayout ParentStackLayout = (StackLayout)Switch_ToggledHandler.Parent;
Label configLabel = (Label)ParentStackLayout.Children[0];
if (Switch_ToggledHandler.IsToggled)
{
switch (Switch_ToggledHandler.name)
{
case "wifi":
configLabel.Text = "wifi open";
break;
case "sound":
configLabel.Text = "sound is open";
break;
default:
Console.WriteLine("Default case");
break;
}
}
else {
switch (Switch_ToggledHandler.name)
{
case "wifi":
configLabel.Text = "wifi off";
break;
case "sound":
configLabel.Text = "sound is off";
break;
default:
Console.WriteLine("Default case");
break;
}
}
}
}
Here is a gif:

I also upload my demo here and you can check it. Let me know if it works for you.
Label
as placeholder for text andSwitch
to toggle. My idea was to capture the binding object on the event to get what exact value user wants to modify. - 3not3CommandParameter="{Binding .}"
, then you can get that value from thesender
in your event handler - Jasonhttps://stackguides.com/questions/41070613/xamarin-forms-switch-toggled-event-doesnt-bind-with-viewmodel
post - 3not3