Beth
Beth

Reputation: 267

How can the ViewModel request an update in the View in WPF/MVVM?

I have a dependency property on a control in my View that is bound to a field on my ViewModel. When the user clicks a menu item I want the control to update the value of that property so the ViewModel can save it in an XML file. What is the correct mechanism to have the ViewModel request that the View update that property?

Upvotes: 1

Views: 1461

Answers (3)

hasi05
hasi05

Reputation: 234

I had the problem that the viewmodel was not updated when clicking on a menuitem right after writing in a TextBox.

With the parameter UpdateSourceTrigger=PropertyChanged, it worked for TextBoxes:

<TextBox Grid.Column="5" Grid.Row="7" Text="{Binding SelectedPerson.Room, UpdateSourceTrigger=PropertyChanged}"></TextBox>

But unfortunately not for DatePickers...

The strange thing is that when clicking on a button instead of the menuitem, the DatePicker is updating the viewmodel. As I don't have more time to look for a bugfix right now, I'll just change my menuitems into buttons.


Edit: the Problem is not the menuitem but the menu itself. When I move the menuitems out of the menu, it works.

Upvotes: 1

Karel Frajt&#225;k
Karel Frajt&#225;k

Reputation: 4489

Your object must implement INotifyPropertyChanged interface and your properties should look like this

private string _property;
public string Property
{
  get { return _property; }
  set 
  { 
    if(_property == value) return;
    _property = value;
    RaisePropertyChanged("Property");
  }
}

so every change made to the property will be cascaded to view through the binding mechanism.

The menu item command property will be bound to a command declared in the view model and it will trigger a method on view model and set the property value. The change will be cascaded to view:

menuItem.Click -> menuItem.Command.Execute -> viewModel.method -> change the view model property -> raise property changed event -> view property changed through binding

Upvotes: 0

GazTheDestroyer
GazTheDestroyer

Reputation: 21251

Generally with MVVM controls update their bound properties (not fields) immediately as they are edited. The ViewModel is the "state", the View is just one way of seeing that state.

Your control should update the ViewModel whenever it is edited. Your ViewModel can then save it to XML when the menu command is invoked.

Upvotes: 1

Related Questions