【问题标题】:How to call a method from another class using WPF commands for buttons? [duplicate]如何使用按钮的 WPF 命令从另一个类调用方法? [复制]
【发布时间】:2014-09-26 01:46:26
【问题描述】:

我是 WPF 新手,我一直在互联网上搜索,但没有找到解决问题的方法。我的问题是,您如何使用命令从另一个类中调用不在代码中的方法?我是否正确命令是从另一个类调用方法的唯一方法?我知道您可以简单地在按钮单击中创建一个对象引用,但由于我的项目的复杂性,我不想这样做。

假设我想使用 MainWindow.xaml 中按钮内的 Command 函数从 ClassA 调用 Print 函数,我该如何实现呢?

ViewModel:ClassA.cs

public class ClassA
    {
        Print()
        {
           Console.WriteLine("Hello");
        }
    }

查看:MainWindow.xaml

<button Command=? ><button/>

【问题讨论】:

标签: c# wpf xaml command commandparameter


【解决方案1】:

如果ClassA 是您视图的DataContext,您可以声明这样的按钮(假设您在类中有一个名为PrintCommandICommand):

<Button Content="Print" Command="{Binding PrintCommand}" />

我会推荐这个 MVVM 教程:

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

使用教程中的 RelayCommand 类,ViewModel 中的相关部分可能如下所示:

private RelayCommand printCommand;
public RelayCommand PrintCommand
{
    get { return printCommand?? (printCommand = new RelayCommand(param => ExecutePrintCommand())); }
}

private void ExecutePrintCommand()
{
    // your code here
}

【讨论】:

  • 非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 1970-01-01
相关资源
最近更新 更多