Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Application using a global variable

I created a WPF application in c# with 3 different windows, Home.xaml, Name.xaml, Config.xaml. I want to declare a variable in Home.xaml.cs that I can use in both the other forms. I tried doing public string wt = ""; but that didn't work.

How can I make it usable by all three forms?

like image 595
Jake Avatar asked Jul 21 '09 20:07

Jake


3 Answers

The proper way, especially if you ever want to move to XBAPP, is to store it in

Application.Current.Properties

which is a Dictionary object.

like image 159
Henk Holterman Avatar answered Oct 15 '22 20:10

Henk Holterman


To avoid having to pass around values between windows and usercontrols, or creating a static class to duplicate existing functionality within WPF, you could use:

  • setting: App.Current.Properties["NameOfProperty"] = 5;
  • getting: string myProperty = App.Current.Properties["NameOfProperty"];

This was mentioned above, but the syntax was a little off.

This provides global variables within your application, accessible from any code running within it.

like image 27
Dustin Pauze Avatar answered Oct 15 '22 19:10

Dustin Pauze


You can use a static property:

public static class ConfigClass()
{
    public static int MyProperty { get; set; }
}

Edit:

The idea here is create a class that you holds all "common data", typically configurations. Of course, you can use any class but suggest you to use a static class. You can access this property like this:

Console.Write(ConfigClass.MyProperty)
like image 17
Eduardo Cobuci Avatar answered Oct 15 '22 18:10

Eduardo Cobuci