Bad
Bad

Reputation: 5299

How to share data among multiple views

In Windows 10 UWP it is possible to create multiple windows (aka views which contain a separate window and a thread) for a single app:

But what is the right way to share data / objects among multiple views in UWP? No info on this is provided in MSDN. There is a good article on this topic: Windows 10, UWP, Multiple Windows, ViewModels and Sharing State. The difficulty is that App.xaml is separately instantiated for each view. It's interesting to see what others are doing in a similar situation?

A similar question which relates to pages but not views: (UWP) Best practice for sharing data between pages

Upvotes: 4

Views: 1322

Answers (1)

Romasz
Romasz

Reputation: 29792

While working with this you have multiple views, but still one application. The most important thing here is mentioned at MSDN you have linked:

Each window operates in its own thread.

This complicates a situation in case of sharing data. As you have one application, you can share some data in app class, but you must look out for few things:

  • UI elements can be accessed only via Dispatcher thread and in this case the one that owns them (so you cannot share this),
  • concurrent access to collections - as there are few threads that can simultaneously access/modify them, use Thread-Safe collections, also some help here,
  • in case of synchronization, you also may need some primitives to steer your application workflow,
  • race conditions - design your app with caution.

Some more help you can find at many blogs/posts. For example at Alabhari's one.

Upvotes: 4

Related Questions