简体   繁体   中英

WPF binding between ViewModel and Model

After a major edit to this quesiton, I'm hoping it's now clear.

I'm very lost with binding in WPF when 1 change should affect multiple properties.

I regularly use VVM to bind my ViewModel to my View and I would say I'm OK with it.

I am trying to implement a state controller. This means that, what ever settings I made in part of my UI, the reflection is through out.

For example in my part of my UI, I can toggle a feature on or off, such as "show images"

When I make this change, I'd like everything in my application to be notified and act accordingly.

So, my StateController class will have a property

public bool ShowImages

And in my View, I'd likely have something like

<image Visible ="{Binding ShowImages", Converter={StaticConverter ConvertMe}}" />

The problem I have is how I go about making the StateController alert all of my ViewModels of this.

Currently, in each ViewModel I'm assuming I'd have to have the same property repeated

public bool ShowImages

EG

public class StateController : BaseViewModel
{
    public bool ShowImages{get;set;}//imagine the implementation is here
}

public class ViewModelB : BaseViewModel
{
    public bool ShowImages{}//imagine the implementation is here
}

public class ViewModelB : BaseViewModel
{
    public bool ShowImages{}//imagine the implementation is here
}

So, my question is, if I updated ViewModelB.ShowImages, how would I first inform the StateController which in turn updates all ViewModels.

Is this something the INotifyPropertyChanged can do automatically for me since they all share the same propertyName, or do I have to implement the logic manually, eg

public static class StateController
{
    public bool ShowImages{get;set;}//imagine the implementation is here
}

public class ViewModelA : BaseViewModel
{
    public bool ShowImages
    {
        get { return StateController.ShowImages; }
        set { StateControllerShowImages = value;
              OnPropertyChanged("ShowImages"); }
     }
}

public class ViewModelB : BaseViewModel
{
    public bool ShowImages
    {
        get { return StateController.ShowImages; }
        set { StateControllerShowImages = value;
              OnPropertyChanged("ShowImages"); }
     }

}

I hate the idea of the above implementation but it does show what I'm trying to achieve. I just hope there is a better way!

To avoid code repetition you can create a class derived from BaseViewModel that implements your property and have ViewModelA , ViewModelB extend it. However, this does not solve the problem of keeping each instance updated.

In order to do so, you may:

  • Use a static class (your current solution) or a Singleton as suggested in one of the comments. This is simple but has potential problems such as race conditions and coupling.
  • Have your ShowImages binding property repeated in each ViewModel and update it by subscribing to a ShowImagesChanged event. This could be published through a Command executed from the UI. I'd say this is the WPF approach and has the benefit of decoupling the ShowImages state management from its consumption.
  • Assign the ShowImages update responsibility to a single ViewModel and subscribe to the its PropertyChanged in the other ViewModels so that they update accordingly. Better than the first option, but still huge coupling.

The PropertyChange notification is only raised for that one object model.

So raising a change notification of the "Name" property of ClassA will only update the UI in cases where it's bound to that specific ClassA.Name . It won't trigger a change notification for any ClassB.Name , or other instances of ClassA.Name .

I would suggest using a Singleton here for your StateModel , and having your other models subscribe to the StateModel.PropertyChanged event to know if it should update, like this answer .

public ViewModelA
{
    public ViewModelA()
    {
        StateController.Instance.PropertyChanged += StateController_PropertyChanged;
    }

    void StateController_PropertyChanged(object sender, NotifyPropertyChangedEventArgs e)
    {
        // if singleton's ShowImages property changed, raise change 
        // notification for this class's ShowImages property too
        if (e.PropertyName == "ShowImages")
            OnPropertyChanged("ShowImages");
    }

    public bool ShowImages
    {
        get { return StateController.Instance.ShowImages; }
        set { StateController.Instance.ShowImages = value; }
    }
}

If I understood you correctly, you are looking for a mechanism that allows your different ViewModels to communicate between each other.

One possible way would be to implement the Observer Pattern (a code example can be found here: "Observer pattern with C# 4" ). In this way your ViewModel subscribe each other to receive change notifications from a "publisher", ie the ViewModel that had its value changed. You have a good control over who receives which notification from which publisher. The downside of this approach is a tight coupling between your models.

My approach would be this:

Use a message dispatcher. Your ViewModels can subscribe to a certain type of message, eg ShowImagesChanged . If any of your ViewModels changed the ShowImages property, that ViewModel calls the dispatcher to send out such a ShowImagesChanged message with your current values.

This way you can keep you ViewModels decoupled from each other. Still, although the ViewModels do not know each other this gives a way to exchange data between them.

Personally, I have used the Caliburn Micro MVVM framework several times for this, but there should be enough other MVVM frameworks that provide the same functionality to fit your taste.

The Calibiurn Micro documentation and how easily the dispatcher can be used is here: Event Aggregator

Why repeat properties at all? Just bind to StateController itself. Say we have singleton StateController :

public class StateController : INotifyPropertyChanged
{
  private static StateController instance;
  public static StateController Instance {
     get { return instance ?? (instance = new StateController()); }
  }

  //here`s our flag
  private bool isSomething;
  public bool IsSomething
  {
     get { return isSomething; }
     set
     {
        isSomething = value;
        PropertyChanged(this, new PropertyChangedEventArgs("IsSomething"));
     }
  }

  private StateController(){}

  public event PropertyChangedEventHandler PropertyChanged = delegate { };
}

Then in base VM class just make a reference to this controller:

public StateController Controller { get { return StateController.Instance; } }

And where needed bind like this:

<CheckBox IsChecked="{Binding Controller.IsSomething}">
    Test
</CheckBox>

This way every binding will work with one property and react to one property. If you need some custom code to work you can subscribe to PropertyChanged of StateController where needed and take action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM