【发布时间】:2022-01-10 05:46:54
【问题描述】:
我以这样一种方式解决了这个问题,即代码隐藏中有一个EventHandler,然后调用ViewModel的相应Command。
<Storyboard x:Key="StartNewGameAnimation" RepeatBehavior="1x"
Completed="StartAnimationCompleted">
private void StartAnimationCompleted(object sender, EventArgs e)
{
var gameBoardViewModel = (GameBoardViewModel)this.DataContext;
gameBoardViewModel.StartGameWhenStartanimationCompletedCommand.Execute(null);
}
这个解决方案工作正常,但我想直接在 Xaml 中处理 Event 并调用 Command。这条路是否存在对我来说很重要。
【问题讨论】:
-
也许您可以使用EventToCommand 实现。
-
你所做的没有错。您可以通过向控件添加 ICommand 类型的 StartGameCommand 属性来改进您的代码,以便将其与实际视图模型分离(考虑让它实现 ICommandSource)。然后在代码隐藏中调用此命令 - 此时视图模型/DataContext 是未知的。然后在 XAML 中将视图模型命令绑定到控件的 StartGameCommand 属性。这样控件就不必知道视图模型(类型转换被删除)。它现在可以使用任何类型进行操作,即 DataContext 独立。
标签: c# wpf events binding command