1

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/>
user3854148
  • 49
  • 3
  • 9
  • http://stackoverflow.com/questions/12422945/how-to-bind-wpf-button-to-a-command-in-viewmodelbase/12423962#12423962 – yo chauhan Aug 03 '14 at 12:04

1 Answers1

1

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
}
Flat Eric
  • 7,971
  • 9
  • 36
  • 45