Home > Software engineering >  how to share a variable between two usercontrol hosted inside a form in the main window WPF C#
how to share a variable between two usercontrol hosted inside a form in the main window WPF C#

Time:08-27

I Have a mainWindow which has a form that take most of the mainWindow. inside the form, i have usercontrols where each one takes the entire form each time.

for example first i have usercontrol which has all the settings that i want to store in variables like names, age and so on then i want to show the name in the next usercontrol.

i'm new to wpf so am not using MVVM, how i can store variables in one usercontrol then access them from the other usercontrol, i saw alot of method but i could not implement them corrctly.

(my main idea is that i want to make a card game where i have seperate window for settings and for the game and so on without the need to hide previous controls and show new one for the next step) if there is a better way than a form i'm open for suggestions.

  • didnt put any code because my question is general but i can post them if you want

CodePudding user response:

If you wanna share a variable between different user controls you can define it globally in MainWindow:

public static int age = 0;
public static string name = 0;

You can then access them from every usercontrol.

Also, I will suggest you to create a class for all of these variables as it will be easier for you to access them. Furthermore, you can see here...

CodePudding user response:

Implement an event at the settings control, give the game user control a reference to the settings user control and let it subscribe to the event. Whenever the event is fired (or invoked) by the settings control, the game control can update its contents.

Maybe get used to events with a simple example before you apply that concept to your WPF project.

  • Related