JensPfister1
JensPfister1

Reputation: 55

MVVM SelectedItem.Property OnChanged

I'm new with MVVM and I'm stuck...

I have a ListBox in the MainWindow. The ListBox contains Items of type WhatEverViewModel which are displayed by DataTemplates. The user can interact with these items and the WhatEverViewModel has several DependencyProperties which may change during interaction.

The question I have is: How can I elegantly react (in the MainWindowViewModel) to changes of DependencyProperties of the CURRENTLY SELECTED WhatEverViewModel. I personally would implement some events in the WhatEverViewModel and when the SelectedItem of the ListBox change, I would attach to the events of the currently selected WhatEverViewModel. But I think in MVVM there might be a more elegant way to solve this...

Thank you.

Upvotes: 2

Views: 350

Answers (3)

blindmeis
blindmeis

Reputation: 22445

communication between viewmodel can be done in several ways.

  • Messenger/Mediator like the one form MVVM Light
  • Eventstuff like the one from PRISM
  • or simply use harcoupling and subscribe to the events from the WhatEverViewModel in your mainviewmodel.

btw why in hell to you use DependencyProperties in your Viewmodels? simple Properties with INotifyPropertyChanged are the way to go.

one more thing. why you want to react to changes in the SelectedViewmodel(or better what you want to achieve, with the selected viewmodel.)? if you just want to display some information in your view, simply bind the SelectedViewmodel to it. you should specify your question in that way.

EDIT

The WhatEverViewModel has a list which is also bound to a listbox (in datatemplate) and depending on what I select in the WhatEverViewModel I want to display some kind of "Configurator" in the MainViewModel. – JensPfister1 1 hour ago

why not simply bind the SelectedWhatEverViewmodel.SelectedListEntryProperty to your configurator view? can you post some code?

Upvotes: 2

Kolky
Kolky

Reputation: 2977

You should implement the INotifyPropertyChanged interface on each of your ViewModels. Then when one of your properties changes call the PropertyChanged event, your views will get notifications that the property has changed (as long as your Binding is correct). If a property is a list or collection make sure that the list is based off an INotifyCollectionChanged.

Add a property for the Selected WhatEverViewModel to your MainWindowViewModel, bind that in your ListBox. Then in your MainWindowViewModel you can hook on to the property changes of your Selected WhatEverViewModel.

For more guidance read:

Upvotes: 0

Nicolas Repiquet
Nicolas Repiquet

Reputation: 9265

Make CurrentWhatEver a property of your MainWindowViewModel and bind the Listbox.SelectedItem property on it. This way, MainWindowViewModel knows when the selected WhatEver changes and can register/unregister to events it's interested in.

Upvotes: 2

Related Questions