Reputation: 112
Good day, I have an app that I'm busy doing for university. A user enters data on the MainWindow.xaml, I want to make the data that they entered on this window accessible throughout the application (Name, Surname etc. I know that I can parse the data into each individual window but I have 13 Windows total.
Is there a way that I can make a global or session variable in WPF that will allow me to access that data anywhere.
I have looked around for answers but using classes etc seems to be a bad way to go and I cant seem to find a solution that will work.
Thanks in advance.
Upvotes: 0
Views: 6364
Reputation: 169160
Is there a way that I can make a global or session variable in WPF that will allow me to access that data anywhere.
Create a class with static properties:
public class ApplicationContext
{
public static string Name { get; set; }
public static string Surname { get; set; }
}
You can then access these properties from any other class in your application:
//set:
ApplicationContext.Name = "name...";
//get:
string name = ApplicationContext.Name;
You could also use the Application.Current.Properties
collection if you don't want to create your own class for some reason:
//set;
Application.Current.Properties["Name"] = "name";
//get:
string name = Application.Current.Properties["Name"].ToString();
Upvotes: 3
Reputation: 4038
You can always mark your variables as public static, so they can be accessed from anywhere. You could simply create a static class that holds all your "global" data.
Another option is making the properties of your MainWindow
class static but this would result in clustering information onto a class that is actually an interface, not a storage.
Probably the best thing to do is the following:
Person
with all the variables needed to describe the person (name, surename, etc.)Person
MainWindow
write your values into the propertyThere you go, you have a static (global) accessible instance of your data-collection that can be extended and has proper encapsulation and naming.
Something to add: There is no such thing as a "Session" or "Global" variable in C#. You can create classes in global space, but not variables and the word "session" reminds me of a webservice which WPF clearly isn't.
Upvotes: 1