Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggering RaisePropertyChanged when Sub Property is changed - MvvmCross

Tags:

c#

mvvm

mvvmcross

I have a class structure setup in the below way - when the Model's Property is changed the RaisePropertyChanged event isn't called. Is there anyway around this or do I need to flatten out the Complex Property inside the ViewModel?

Class ViewModel
{
   public Model model {
                   get { return _Service.GetModel();}
                   set { _Service.SetModel(); RaisePropertyChanged(() => Model);
                  }
} 

class Model
{
   public string A {get;set;}
}

Class Service
{

}
like image 758
Brenton Avatar asked Mar 22 '23 06:03

Brenton


1 Answers

I don't think there's any easy way around it.


Either you can change model so it supports INotifyPropertyChanged - e.g.

class Model : MvxNotifyPropertyChanged
{
   public string A { 
        get { return _a; } 
        set { _a = value; RaisePropertyChanged(() => A); }
   }
}

I've used this first approach when I used a stackoverflow library - which had model entities like http://stacky.codeplex.com/SourceControl/latest#trunk/source/Stacky/Entities/Answer.cs


... or you can wrap your model with another INotifyPropertyChanged class:

class ModelWrapper : MvxNotifyPropertyChanged
{
   private readonly Model _m;
   public ModelWrapper(Model m) 
    { _m = m; }

   public string A { 
        get { return _m.A; } 
        set { _m.A = value; RaisePropertyChanged(() => A); }
   }
}

I've used this approach when I don't have any control over the Model class - when it's been given to me.


... or as an extension of that approach, you can flatten the property down to the parent ViewModel:

class MyViewModel : MvxViewModel
{
   private readonly Model _m;
   public ModelWrapper(Model m) 
    { _m = m; }

   public string A { 
        get { return _m.A; } 
        set { _m.A = value; RaisePropertyChanged(() => A); }
   }
}

I've used this approach only when there are just a couple of properties to worry about.


Overall... remember that the ViewModel is there to be a Model of the View - it's OK to copy property values to/from Model objects.

like image 197
Stuart Avatar answered Apr 26 '23 05:04

Stuart