由于您已从外部绑定上下文传递ViewModel实例,因此应按如下方式设置MVVMContext:
// View(UserControl) side: MVVMContext context = new MVVMContext(); // make sure that the MVVMContext will be destroyed when the UserControl destroyed context.ContainerControl = this; // your View(UserControl) context.SetViewModel(typeof(MyViewModel), viewModel);
这样可以防止自动创建MyViewModel实例(在指定context.ViewModelType时使用自动创建)。
然后您可以像往常一样使用MVVMContext API。
在你的情况下,你可以使用 BindCommand 代替 EventToCommand 因为它专门设计用于处理按钮对象(如BarButtonItems)。 而且,我强烈建议你使用 流畅的API 它提供了非常干净和可维护的代码:
BindCommand
EventToCommand
var fluent = context.OfType<MyViewModel>(); fluent.BindCommand(cmdA, x => x.SomeMethod()); fluent.BindCommand(cmdB, x => x.SomeOtherMethod());