1

I have a MainViewModel, which features PersonViewModel and a HouseViewModel as properties. HouseViewModel has the property GetRooms. What is the best way to access this property from the PersonViewModel?

My solution at the minute is to pass through an instance of MainViewModel to PersonViewModel, then I can call MainViewModel.HouseViewModel.GetRooms. However, this seems a little wasteful.

I am happy to pass a function as a delegate, but I can't seem to do this with a Property. I have searched for an example of this and only come up with overly complicated techniques. I'm assuming there must be a simple way of doing this, as it seems like a common problem. Can anyone point out a strong example?

Or is there another, alternative method that I haven't considered?

Bla...
  • 7,228
  • 7
  • 27
  • 46
jimbo
  • 603
  • 9
  • 27
  • Isn't it more logical that a person gets a room? A house doesn't get a room? A house has rooms that can be 'got' by a person? So why does the House object have a method get a room? Surely the Person object should have that. – Paul Zahra Jul 30 '14 at 08:32
  • This is a fictional example. Please ignore any sort of perceived logic between Person/House/Room. – jimbo Jul 30 '14 at 09:20
  • Ah ok, then take a look at http://stackoverflow.com/questions/16913077/accessing-properties-in-other-viewmodels-in-mvvm-light – Paul Zahra Jul 30 '14 at 09:22
  • `However, this seems a little wasteful.?` What do you mean by this? I feel you can pass HouseViewModel as parameter to PersonViewModel Construction instead of the MainViewModel. If it makes sense to do this - do it, dont over optimize it and it will lead to confusion. Sometimes readability is more important. – Carbine Jul 30 '14 at 10:05
  • Fair enough, but where do you draw the line? What if I need to pass the MainViewModel down through several instances of classes? – jimbo Jul 30 '14 at 10:33
  • Also, Paul Zahra - is that solution not specific to MVVM-Light? – jimbo Jul 30 '14 at 10:34

1 Answers1

2

If a method has to be shared across two viewmodel, it should be defined in base viewmodel or a service. The best way is a common Service class should hold all common methods like GetRooms, CheckIn, CheckOut, etc. And this service should be provided to every viewmodel using Dependency Injection.

public class HomeViewModel
{
    public HomeViewModel(IRoomService roomservice)
    {

    }
}

public class PersonViewModel
{
    public PersonViewModel(IRoomService roomservice)
    {

    }
}
Jawahar
  • 4,775
  • 1
  • 24
  • 47