2

I have the task to write a user control to display some results by using the MVVM patern.

The main application (called ApplicationVM) has two a properties UserControlViewModel and SelectedRecord. The first property contains an instance of the UserControlViewModel. In XAML I use these property to bind the UserControl to the UserControlViewModel. The DependencyProperty PageCount is for simple notifications between a display function in the view and the UserControlViewModel.

<control:UserControl DataContext="{Binding UserControlViewModel}" PageCount="{Binding DocumentPageCount}" />

Here is the implementation of the second property in the ApplicationViewModel.

public Record SelectedRecord
{
    get
    {
        return m_SelectedRecord;
    }
    set
    {
        m_SelectedRecord = value;
        OnPropertyChanged("SelectedRecord");
    }
}

Later, this property will by replaced. But what I should to do is to make a dependency between the property "SelectedRecord" and a "Record" of the "UserControlViewModel" which calls a function to generate the new content (e.g. GenerateContent()). How can I make it possible that a change of the SelectedRecord property updates the Record Property of the UserControlViewModel to genereate the new content? Or can my UserControlViewModel hear the OnPropertyChanged("SelectedRecord") to generate automaticcly new content?

Pyth0n
  • 355
  • 5
  • 13

2 Answers2

4

I would use a messenger - that way your view models can be nicely decoupled.

Here's a thread on SO talking about the one in MVVM light:

MVVM light - how to access property in other view model

Community
  • 1
  • 1
Grokys
  • 16,228
  • 14
  • 69
  • 101
3

One easy solution would be to update the setter of your SelectedRecord property. Here you could call the GenerateContent method on the UserControlViewModel, and possibly also set the SelectedRecord property there if you need to.

Alternatively your UserControlViewModel could listen to the PropertyChanged event on the ApplicationVM, but to do that the UserControlViewModel would need a reference to the ApplicationVM.

Finally you could use an event system to communicate between your view models. This would ensure that your view models were nicely decoupled, but the price would be added complexity. Check out the documentation on the Prism Event Aggregator if you are interested.

Rune Grimstad
  • 35,612
  • 10
  • 61
  • 76