0

I have multiple ViewModels and use ViewModelBase as an abstract class in all of them. I want to grab the current property values from one class in another. Creating an instance is not desirable, making the property static gets me what I want. However by doing this I lose out on the INotifyPropertyChange Im using with ViewModelBase.Set() since Set() is a non-static method.

Whats the alternative where I can get the property value, yet still keep the benefits of ViewModelBase in MVVM?

public class SampleViewModel : ViewModelBase
{
   private static bool _sample;
   public SampleViewModel()
   {
   }
   public static bool GetValue
   {
      get { return _sample; }
      set { Set(ref _sample, value); }
   }
}

public class MyClassViewModel : ViewModelBase
{
   public MyClassViewModel()
   {
      bool myValue = SampleViewModel.GetValue;
   }
}
GET1NE
  • 61
  • 1
  • 9
  • 1
    Why do you not want to create an instance variable? Static means it has no whatsoever relation to the instance. Is your static property not related to your instance at all? If it is, your design is flawed by setting is as static – Hasan Emrah Süngü Nov 17 '16 at 02:15
  • Don't use static property. Do you have main ViewModel? – Bigeyes Nov 17 '16 at 02:16
  • @EmrahSüngü By creating instance variable I miss out on the current data since its already been set. If there was a way to reference that instance it would get me what I want. – GET1NE Nov 17 '16 at 02:17
  • @Bigeyes I do have a main ViewModel – GET1NE Nov 17 '16 at 02:18
  • If it is already set then why not pass that already set data to your instance variable? – Hasan Emrah Süngü Nov 17 '16 at 02:19
  • @EmrahSüngü yes that is one way to do it. Just thought there might be a cleaner way to do it. Also new to MVVM and didn't know if that was best practice. – GET1NE Nov 17 '16 at 03:02
  • @GET1NE Yes, you can have one ViewModel reference an already existing instance of another ViewModel class. How best to do it really depends on what kind of relationship the two viewmodel classes have to each other. It might make sense to have VMA and VMB each reference the other, it might make sense to have VMA reference VMB but not the other way around, or it might make sense to represent the relationship in another layer (such as in the Model), and use some kind of map to look up the related VM object. – PMV Nov 17 '16 at 04:44

1 Answers1

0

ParentVM creates a ChildVM, exposing it via a ChildVM property ParentView handles the resultant PropertyChanged event, creating a ChildView, setting its DataContext to ChildVM.

See here for details.

Or use MVVM Light Toolkit's Messaging Services to pass values to view Models.. But I don't like it.

Community
  • 1
  • 1
Bigeyes
  • 1,508
  • 2
  • 23
  • 42
  • Thanks so I ended up using the later, specifically this http://stackoverflow.com/questions/13795596/how-to-use-mvvmlight-simpleioc – GET1NE Nov 18 '16 at 22:21