问题描述
所以我一直在四处寻找,但无法确切知道如何做到这一点.我正在使用 MVVM 创建用户控件,并希望在加载"事件上运行命令.我意识到这需要一些代码,但我不太清楚需要什么.该命令位于 ViewModel 中,它被设置为视图的数据上下文,但我不确定如何路由它,因此我可以从加载事件后面的代码中调用它.基本上我想要的是这样的......
So I've been searching around and cannot find out exactly how to do this. I'm creating a user control using MVVM and would like to run a command on the 'Loaded' event. I realize this requires a little bit of code behind, but I can't quite figure out what's needed. The command is located in the ViewModel, which is set as the datacontext of the view, but I'm not sure exactly how to route this so I can call it from the code behind of the loaded event. Basically what I want is something like this...
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
//Call command from viewmodel
}
环顾四周,我似乎无法在任何地方找到它的语法.我是否需要先在 xaml 中绑定命令才能引用它?我注意到用户控件中的命令绑定选项不会让您像在按钮之类的东西中那样绑定命令...
Looking around I can't seem to find the syntax for this anywhere. Do I need to bind the command in the xaml first to be able to reference it? I notice the command bindings option within a user control will not let you bind commands as you can within something like a button...
<UserControl.CommandBindings>
<CommandBinding Command="{Binding MyCommand}" /> <!-- Throws compile error -->
</UserControl.CommandBindings>
我确信有一种简单的方法可以做到这一点,但我终其一生都无法弄清楚.
I'm sure there's a simple way to do this, but I can't for the life of me figure it out.
推荐答案
好吧,如果 DataContext 已经设置好了,你可以转换它并调用命令:
Well, if the DataContext is already set you could cast it and call the command:
var viewModel = (MyViewModel)DataContext;
if (viewModel.MyCommand.CanExecute(null))
viewModel.MyCommand.Execute(null);
(根据需要更改参数)
这篇关于从代码后面调用命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!