c# - 如何从 C# 代码中调用 Command 而不是通过将 UI 控件绑定(bind)到它?

标签 c# wpf data-binding icommand

我正在开发 C#-WPF-App。

在窗口中按下某个按钮时,将加载一个模块。发生这种情况是因为按钮的 Command 属性绑定(bind)到类“ConfigureViewModel”中的 LoadModuleCommand:

<Button Command="{Binding LoadModuleCommand}" Margin="10,10,10,10" Grid.Column="1" Content="Add Module" Grid.Row="0" />

出于某种原因,这对于这个问题并不重要,我现在还想从 MainViewModel.cs 文件调用相同的命令(即 LoadModuleCommand),如果某个条件为真:

 if (id.Equals(Module.Id.ToString()))
        {
             //call the LoadModuleCommand

        }

如果我必须将 LoadModuleCommand 绑定(bind)到第二个 UI 控件,我知道我必须做什么。但是我如何简单地从 c# 代码中调用命令呢?

最佳答案

有几种方法可以解决您的问题。

一种方法是获取绑定(bind)的数据上下文并将其转换。现在你可以像这样执行命令了

var viewModel = (ConfigureViewModel)DataContext;
if (viewModel.LoadModuleCommand.CanExecute(null))
{
    viewModel.LoadModuleCommand.Execute(null);
}

请注意,您需要知道数据上下文的类型才能正确转换它。如果可能有多种类型,则使用一个接口(interface)。

第二种方法是命名按钮(例如 <Button x:Name="loadModuleButton" .../> )并引发点击事件,例如

loadModuleButton.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));

关于c# - 如何从 C# 代码中调用 Command 而不是通过将 UI 控件绑定(bind)到它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46757800/

相关文章:

c# 在每 200 个循环后保存 Streamwriter 而不关闭

c# - 用户代码未处理 SqlException

wpf - RichTextBox 并在插入符号位置插入

c# - 只允许 OneWayToSource 绑定(bind)模式

java - 动态生成jsf表单问题

c# - 如何在c#中将json转换为json对象?

wpf - 使用命令绑定(bind)将数据从 View 发送到 View 模型

java - Android 数据绑定(bind)错误 :Execution failed java. lang.RuntimeException:

mysql - 关于更新 MySQL 数据库和我的 devexpress Gauge 值之间的数据问题的数据绑定(bind)问题?

c# - Unity android插件C#代码启动activity