如何在C# UWP的ListView中获取ToggleSwitch实例?
Hey there! Sorry to hear your previous attempt to resolve this didn't work out—misdiagnosing the root cause as a binding issue can definitely throw you off track. Let's tackle this ToggleSwitch-in-ListView problem head-on, since you've already confirmed your jointList data is complete.
Below are the most common non-binding-related issues and their fixes:
1. Fix Toggle State Glitches from ListView Item Reuse
If your ToggleSwitch states get mixed up when scrolling, this is almost certainly due to ListView's item container reuse mechanism. Here's how to fix it:
- Add a boolean property (like
IsToggleActive) to your data model class to store the toggle state for each item. This isn't about XAML binding—it's just a place to persist the state so we can sync it back to the control later. - Hook up the
Toggledevent of your ToggleSwitch to save the state to the data item:
private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e) { var toggle = sender as ToggleSwitch; var item = toggle.DataContext as YourJointListItemModel; if (item != null) { // Save the toggle state directly to the data item item.IsToggleActive = toggle.IsChecked.Value; // Add your custom business logic here (e.g., update a database, trigger an action) } }
- Use the
LoadingRowevent to restore the toggle state when an item container is reused:
private void ListView_LoadingRow(object sender, ListViewLoadingRowEventArgs e) { var item = e.Row.DataContext as YourJointListItemModel; var toggle = e.Row.FindName("YourToggleSwitchName") as ToggleSwitch; if (toggle != null && item != null) { // Sync the saved state back to the ToggleSwitch toggle.IsChecked = item.IsToggleActive; } }
2. Ensure ToggleSwitch Events Actually Fire
Sometimes the ToggleSwitch feels unresponsive because other elements are blocking it or interfering with events:
- Check if your
ListViewItemhasIsHitTestVisible="False"—this would make the entire item unclickable, including the ToggleSwitch. Set it toTrueif that's the case. - If you're using the ListView's
ItemClickevent, avoid settinge.Handled = truein that handler. Doing so can stop the ToggleSwitch'sToggledevent from bubbling up. - Double-check that the ToggleSwitch's
IsEnabledproperty isn't being set toFalsesomewhere in your code or XAML.
3. Manual State Control for Bulk Operations
If you need to do things like select/deselect all toggles, make sure you're updating the data model directly instead of trying to manipulate the controls:
// Example: Select all toggles foreach (var jointItem in jointList) { jointItem.IsToggleActive = true; } // Refresh the ListView to sync the updated state to the UI yourListView.Items.Refresh();
This approach avoids issues with control reuse because we're working with the source data, not the UI elements themselves.
内容的提问来源于stack exchange,提问作者positive perspective

