Search code examples
wpfmvvm-light

ViewModels members not updated on Command


I'm using MVVM light toolkit to handle a button click. If I do:

CustomerSaveCommand = new RelayCommand(
    () => CustomerSave(),
    ()=> true);

private void CustomerSave() {
    customer.Address="My Street";
}

The function is invoked but the Address field bound in the UI is not updated.

If I put customer.Address="1234" in the ViewModel constructor, the UI IS updated. What am I doing wrong?

EDITED:

The problem is really strange: if I do viewModel.customer.City = "CITY1" in the window load it runs, if I add a button and, in the code-behind click, I add viewModel.customer.City = "CITY2" it does not work.


Solution

  • The customer object in your viewmodel needs to implement the INotifyPropertyChanged interface.

    Then in the Address Property setter, you would invoke the PropertyChanged event.

    Alternatively, your viewModel can implement the INotifyPropertyChanged interface, and could wrap the Address property and call the PropertyChanged event. You would have to update your bindings, but your model objects wouldn't have to implement any interfaces.

    The reason you're seeing that the address is showing up when you modify the object in the constructor is because binding has not taken place yet. In order for the UI to be updated you need to instruct the binding engine that a property binding has changed. To do that you use the INotifyPropertyChanged interface.