为何WPF中ICommand对象需设为public才能正常工作?
Hey there! Let's break down why your EditCommand isn't triggering when you click the button—this is a super common gotcha when starting out with MVVM, so you're definitely not alone here.
The Root Cause: XAML Binding Can't Access Private Members
When you bind a button's Command property to EditCommand in your XAML, the MVVM binding engine (whether it's WPF, Xamarin, or another framework) only has access to public properties on your ViewModel. Since you declared EditCommand as private, the binding engine can't see it at all. That means when you click the button, there's no command to trigger—hence the unresponsive behavior or binding error you're encountering.
Why the Video Uses Public
MVVM's core pattern relies on the View (your XAML) interacting with the ViewModel through exposed public members. Commands are the ViewModel's way of letting the View trigger actions, so they need to be public properties the View can reach. The course uses public for exactly this reason—it's a fundamental rule of how data binding works in MVVM.
How to Fix It
Here's the step-by-step fix to get your command working:
- Update the command's access modifier to public:
Make sure your command is a public property (not just a field) so the binding engine can access it:// 把private改成public,保持属性的结构 public ICommand EditCommand { get; } - Initialize the command in your ViewModel constructor:
Assuming you're using a common command implementation likeRelayCommandorDelegateCommand(which the course likely covers), wire it up to yourEditCoffeemethod:public YourCoffeeViewModel() { // 关联命令和你的编辑方法 EditCommand = new RelayCommand(EditCoffee); } // 你的编辑方法可以保持private,因为命令会调用它 private void EditCoffee() { // 这里放你的咖啡编辑逻辑 } - Verify your XAML setup:
Double-check that your button's command binding points toEditCommandcorrectly, and that your ViewModel is properly set as the View'sDataContext(this is usually done in XAML or code-behind, and the course should have walked through this step).
Quick Debug Tip
If you're still stuck, open the Output Window in Visual Studio while debugging. Look for binding error messages—they'll explicitly tell you if the engine can't find the EditCommand property, which confirms the access modifier is the issue.
内容的提问来源于stack exchange,提问作者bezbos.

