0

I have the following in my ViewModel:

public MyViewModel() {
  CloseCommend = new RelayCommand(closeWindow);
}

public RelayCommand CloseCommend;
private void closeWindow() {
  Application.Current.MainWindow.Close();
}

XAML:

<Button ... Command="{Binding CloseCommend}"/>

I see the ViewModel constructor is initialized so the binding should be there. But when I click the close button, nothing happens. Any ideas what I'm doing wrong?

Amitd
  • 4,769
  • 8
  • 56
  • 82
4thSpace
  • 43,672
  • 97
  • 296
  • 475

1 Answers1

4

Change from a field definition to a property definition:

public RelayCommand CloseCommand { get; set; }

Why:

Fields are typically, not bindable. Check out the Binding Sources Overview

You can bind to public properties, sub-properties, as well as indexers, of any common language runtime (CLR) object. The binding engine uses CLR reflection to get the values of the properties. Alternatively, objects that implement ICustomTypeDescriptor or have a registered TypeDescriptionProvider also work with the binding engine.

For more information about how to implement a class that can serve as a binding source, see Implementing a Class for the Binding Source later in this topic.

Under the "Other Characteristics" section:

You cannot bind to public fields.

Michael G
  • 6,695
  • 2
  • 41
  • 59