2

I'm trying to execute a RelayCommand (which is in my CodeBehind) using the RelayCommand from Galasoft MVVMLight.

MainPage.xaml.cs

public MainPage()
{
    InitializeComponent();
    DataContext = this;
    MyCommand = new RelayCommand(Methode);
}

#region Commands
public RelayCommand MyCommand { get; private set; }
#endregion

private void Methode()
{
    int i = 1;        
}

MainPage.xaml:

<Button Command="{Binding MyCommand}"/>

Unfortunately, the command is not firing/the method is not being called. Other binded elements like ImageSource, ... are working fine.

daniele3004
  • 13,072
  • 12
  • 67
  • 75
Rudi
  • 926
  • 2
  • 19
  • 38

1 Answers1

9

Try creating the new RelayCommand before setting the DataContext.

Setting the DataContext triggers the data binding engine to update the bindings. Since the MyCommand property is not set yet, the Buttons Command will be null. Creating a new RelayCommand after setting the DataContext will not notify the Button of the update to the property.

Creating the Command before setting the DataContext is one solution, another one is implementing the INotifyPropertyChanged interface and raising the PropertyChanged event after setting MyCommand (or in the setter, requiring a backing field).

Roel van Westerop
  • 1,400
  • 8
  • 17
  • working, thanks... Didn't know it's that simple. Also thought it would make no difference if I set the DataContext at the beginning or at the end. – Rudi Aug 28 '14 at 11:05
  • 1
    It makes a difference in this case, since setting the datacontext triggers the updates for the bindings. The Command binding finds your command property, but it isn't set yet. After setting the datacontext, setting the command property doesn't notify your button it has changed, so the button won't know that. – Roel van Westerop Aug 28 '14 at 11:07
  • No problem, should have done that in my answer in the first place, I'll update it. – Roel van Westerop Aug 28 '14 at 11:12