Search code examples
c#wpfxamlcommandcommandparameter

How to call a method from another class using WPF commands for buttons?


I am new to WPF and I've been searching all over the internet and have not found a solution to my problem. My question is, how do you call a method not in the code behind but from another class using Commands? Am I correct that Commands are the only way to call methods from another class? I know you can simply make an object reference inside the button click, but I don't want to do that due the complexity of my project.

Let's say I want to call the Print function from ClassA using the Command function inside the button in MainWindow.xaml, how can I achieve this?

ViewModel: ClassA.cs

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

View: MainWindow.xaml

<button Command=? ><button/>

Solution

  • If ClassA is the DataContext of your view you can declare a button like this (assuming you have an ICommand named PrintCommand inside the class):

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

    I would recommend this tutorial for MVVM:

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

    Using the RelayCommand class from the tutorial, the relevant part in the ViewModel could look like this:

    private RelayCommand printCommand;
    public RelayCommand PrintCommand
    {
        get { return printCommand?? (printCommand = new RelayCommand(param => ExecutePrintCommand())); }
    }
    
    private void ExecutePrintCommand()
    {
        // your code here
    }