I currently have a listview which displays a list of "ConfigurationItem" objects. Each row displays a "ConfigurationItem"'s Name and Status properties in a label and has a Switch hooked up to It's Checked property value.
When I toggle a switch for a listview item I want to get the "ConfigurationItem" for that corresponds with that switch and the value of the switch so I can change the Checked property value for the "ConfigurationItem". Currenlty I've added an eventhandler for the Toggled event which receives the switch as sender but I can't figure out how I can get the "ConfigurationItem" object that corresponds with the toggled switch. Can someone please explain how I can achieve this?
XAML
<ListView x:Name="ConfigurationItemListView" BackgroundColor="Transparent"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <StackLayout Orientation="Horizontal"> <StackLayout Orientation="Vertical"> <Label Text="{Binding Name}" TextColor="#fff" HorizontalOptions="FillAndExpand" FontAttributes="Bold"/> <Label Text="{Binding Status}" HorizontalOptions="FillAndExpand" TextColor="#fff" FontSize="Micro"/> </StackLayout> <Switch IsToggled="{Binding Checked}" HorizontalOptions="EndAndExpand" Toggled="OnItemToggled"/> </StackLayout> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView>
C#
private Room currentRoom { get; set; } public ConfigurationItemPage() { InitializeComponent(); }
//Room selected public ConfigurationItemPage(Room room) { InitializeComponent(); currentRoom = room; this.Title = currentRoom.Name; GetConfigurationItems(); MessagingCenter.Subscribe<ConfigurationItemDetailsPage>(this, "GetConfigurationItems", (sender) => GetConfigurationItems()); ConfigurationItemListView.ItemSelected += OnItemSelected; }
async void OnItemSelected(object sender, SelectedItemChangedEventArgs e) { if (ConfigurationItemListView.SelectedItem != null) { await Navigation.PushModalAsync(new ConfigurationItemDetailsPage((ConfigurationItem)e.SelectedItem)); } ((ListView)sender).SelectedItem = null; }
public void OnItemToggled(object sender, ToggledEventArgs e) { //Get ConfigurationItem (listview item) //save switch value Switch toggledSwitch = (Switch)sender; }
public async void GetConfigurationItems() { LoadingActivityIndicator.IsRunning = true; LoadingActivityIndicator.IsVisible = true; ConfigurationItemService configurationItemService = new ConfigurationItemService(); IEnumerable<ConfigurationItem> configurationItems = await configurationItemService.GetByRoomId(currentRoom.Id); ConfigurationItemListView.ItemsSource = configurationItems; LoadingActivityIndicator.IsRunning = false; LoadingActivityIndicator.IsVisible = false; }