Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RelayCommand not executing

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.

like image 330
Rudi Avatar asked Jun 12 '26 06:06

Rudi


1 Answers

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).

like image 139
Roel van Westerop Avatar answered Jun 14 '26 18:06

Roel van Westerop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!