MAUI控件中SwipeItem绑定RelativeSource的DeleteCommand无法触发问题排查
Let's cut straight to the issue: your DeleteCommand isn't triggering because the Delete method in your MainViewModel is marked as private, which causes the CommunityToolkit.Mvvm source generator to create a private DeleteCommand property. XAML data binding can only access public properties, so it can't see the command at all.
How to Fix It
1. Fix the Method Access Modifier
Change the Delete method from private to public (or internal if that fits your project's access rules):
[RelayCommand] public void Delete(string s) { if (Items.Contains(s)) { Items.Remove(s); } }
The CommunityToolkit.Mvvm generator mirrors the access level of your method when creating the corresponding command property. A public method will generate a public DeleteCommand that XAML can bind to successfully.
2. Double-Check Your Binding Setup (Optional)
Your XAML binding for the SwipeItem is actually written correctly—using RelativeSource to traverse up to the MainViewModel and passing the current item as CommandParameter is the right approach. If you still run into issues after fixing the method access, verify these two things:
- Ensure your
MainPagehas itsBindingContextset to an instance ofMainViewModel(either in code-behind or XAML) - Confirm the string items in your
ObservableCollectionare reference-consistent (since you're usingContainsandRemove, identical string literals work fine here, but if you were using custom objects you'd need to handle equality properly)
Quick Debug Tip
To confirm the command is being generated correctly, add a debug line in your ViewModel constructor:
public MainViewModel() { Items = new(); Items.Add("test"); // Verify the command exists and is accessible System.Diagnostics.Debug.WriteLine(DeleteCommand?.ToString() ?? "DeleteCommand is null"); }
After making these changes, your swipe-to-delete functionality should work exactly as expected.
内容的提问来源于stack exchange,提问作者Andrija

