从后台代码调用命令 [英] Call Command from Code Behind

查看:90
本文介绍了从后台代码调用命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我一直在搜索,无法确切地知道如何执行此操作。我正在使用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);

(根据需要更改参数)

这篇关于从后台代码调用命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆