0

I have a class named as pendingData with a list of objects and it instantiated with the start of the application and will remain as long as application runs. But I have to change add objects to the list. How can I access that object in other view without passing the object in the constructor?

So, is there a broadcasting method or any way to do that?

And pendingData class is instantiated only once.

Naresh Ravlani
  • 1,600
  • 13
  • 28
kirito70
  • 65
  • 2
  • 14

1 Answers1

1

To ensure you only get one instance of your object you could use the singleton pattern like this

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }
}

You'll notice the constructor is private so you must obtain an instance through the Instance method. You'll also notice that method only creates an instance of the object if it doesn't exist.

You could use the same Singleton object for all your views knowing that it'll be the same one and therefore the same data.

Alternatively, you could just declare it in a central location, you main window's viewmodel perhaps, and then everything else could access it from there.

As for updating it you could pass a reference to your object to each place that it's used and then update it directly. Or you could do something with events like this

In your view's viewmodel

public static event EventHandler MyEvent;

private void OnMyEvent()
{
    if (MyEvent != null)
    {
        MyEvent(this, new EventArgs());
    }
}

In the location where your data object is, perhaps your main window's view model

MyView.MyEvent += delegate
{
    // Update your data
};

If you can't have multiple views open and/or don't want your views to respond to data changes once opened then this is probably enough. However, if you want your views to respond to data in real time you could do something with events so one view can tell another view that the data has changed and that it needs to update.

Gareth
  • 913
  • 6
  • 14
  • As I have to update **Pending Items List** in other view, So I have to make events and call them to tell the view with **Pending Items List** that object has been updated. And for that purpose I would be using MVVM Messenger as @Naresh Shared a thread in above comments? – kirito70 Jun 15 '17 at 09:13
  • You could, but you don't have to. It's possible with or without it. To do it the Messenger way you'd be going down the MVVM Light route. Before you do this I suggest you have a look at MVVM Light - http://www.mvvmlight.net/ - and see what additional benefits/costs it adds to your project. – Gareth Jun 16 '17 at 07:17