1

Is it possible to make a variable or a List of items accessible to the whole project? My program selects an object in one view and a I want to have access/change it another one.

I know this not the best workaround and it would be better to use a MVVM-pattern for this, but it seems a big effort to implement this properly just for this simple usecase of one ot two variables/lists.

NHQue
  • 73
  • 1
  • 7
  • You could create a `public static class Global { public static List Items { get; set; } }`. You could also just shoot yourself in the foot. – CodeCaster Nov 19 '21 at 09:57
  • 2
    Why not use Singleton Pattern? – Infosunny Nov 19 '21 at 09:59
  • 1
    Using global variables prevents you from writing good tests. – Jeroen van Langen Nov 19 '21 at 10:01
  • 2
    Why can't the thing that transitions from one view to the other also communicate the necessary data? It sounds like you're seeking to build that well trodden "i logged in and saw someone else's account" security risk – Caius Jard Nov 19 '21 at 10:05
  • 1
    OP means, as I think, that C# instead of direct use `Banana` needs to create `Monkey` in `BananaTree`, which in `Tropics`, which are in `ClimaticZone` in `Planet` to access just the `Banana`. Using global variables isn't good approach, but for simple projects or homeworks - why not? – Auditive Nov 19 '21 at 10:17
  • You could use app settings. – Dark Templar Nov 20 '21 at 17:44
  • @CaiusJard thank you for your answer. How could that be possible? In my case a button is responsible for the transition from one view to the other – NHQue Nov 21 '21 at 14:58
  • 1
    @NHQue take a look at https://stackoverflow.com/questions/56847571/equivalent-to-usersettings-applicationsettings-in-wpf-net-5-net-6-or-net-c – Caius Jard Nov 21 '21 at 17:04

1 Answers1

2

Sharing data can be done in multiple ways.

One interesting way could be to cache the data, have a look at this for example : https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/walkthrough-caching-application-data-in-a-wpf-application?view=netframeworkdesktop-4.8

I would recommend against using any global variables, I would also recommend not using static variables either as you might open yourself up to sharing data between users for example.

In this example, when you need the data, you check if you have it in the cache, if not you load it from wherever ( db, file, api, whatever your source is) and then you simply read it from the cache wherever and whenever you require it.

If you need to update it, then you make sure you update it to whatever storage mechanism you have and then you reload the cache. This is a good way to keep things in sync when updates are needed without complicating the application, its testing and the maintenance.

Andrei Dragotoniu
  • 6,155
  • 3
  • 18
  • 32