WPF Application using a global variable
Asked Answered
G

7

22

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?

Growl answered 21/7, 2009 at 20:2 Comment(0)
P
30

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.

Pyo answered 21/7, 2009 at 20:26 Comment(2)
Properties isn't coming up as a member of Application.Current, is there something special to do in order to access it? EDIT: it just occurred to me that this could be because I'm making a Windows Phone application so I may have slightly different libraries.Burgonet
@dr monk: Win Phone (7) means SilverLight, this answer was about WPF.Pyo
C
30

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.

Chufa answered 5/4, 2011 at 11:31 Comment(2)
what if we need to save class objects? will it work the same way?Bead
I had to add .ToString() to get the value from the property, but other than that, this works fine for me, thanks for sharing. string myProperty = App.Current.Properties["NameOfProperty"].ToString();Casting
D
16

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)
Drift answered 21/7, 2009 at 20:5 Comment(1)
First code snippet doesn't seem to compile. Redundant parentheses on first line?Scepter
P
7

As other people mentioned before either use App.Current.Properties or create a static class. I am here to provide an example for those who need more guidance with the static class.

  1. Add a new Class

Right-click your project name in your solution explorer Add > New Item choose Class give it a name (I usually name it GLOBALS)

  1. What that cs file should look like
using System;

namespace ProjectName
{
    public static class GLOBALS
    {
        public static string Variable1 { get; set; }
        public static int Variable2 { get; set; }
        public static MyObject Variable3 { get; set; }
    }
}
  1. Add references into .cs files where you intend to use those variables

using ProjectName

  1. We're done. Use it. Examples:
GLOBALS.Variable1 = "MyName"
Console.Write(GLOBALS.Variable1)
GLOBALS.Variable2 = 100;
GLOBALS.Variable2 += 20;
GLOBALS.Variable3 = new MyObject();
GLOBALS.Variable3.MyFunction();

A note about unit testing and static classes / static variables

It is generally considered bad practice to use a static class to hold global variables, one of the major reasons being that it can significantly hinder the ability to properly unit test your code.

If however you need code that is testable and you do still want to use a static global variable class, then at least consider using a singleton pattern for accessing your GLOBALS. [more details here: https://jonskeet.uk/csharp/singleton.html]

Below is a useful snippet of what I mean. Make GLOBALS abstract and remove the static, then add the following inside GLOBALS class:

    private static GLOBALS instance = null;
    
    /// <summary>
    /// The configuration instance used by the application and unit tests
    /// </summary>
    public static GLOBALS Instance
    {
        get
        {
            if (instance == null)
            {
                //Create the default configuration provider
                instance = new AppConfigConfiguration();
            }

            return instance;
        }
        set
        {
            instance = value;
        }
    }

AppConfigConfiguration (in the example above) is an application specific settings class which derives from GLOBALS. The singleton pattern allows other configurations to also be derived, and optionally set on the Instance property, a common occurrence being prior to unit tests running so that test specific settings can be assured.

Presbyterial answered 16/4, 2020 at 4:36 Comment(0)
B
2

There are two different things you can do here (among others; these are just the two that come to mind first).

  1. You could make the variable static on Home.xaml.cs

    public static string Foo = "";
    
  2. You could just pass in the variable to all three forms.

I would go with #2, myself, and if necessary create a separate class that contains the data I need. Then each class would have access to the data.

Billington answered 21/7, 2009 at 20:9 Comment(1)
But I want to add a value to the variable in home and use that value in config. If I declare in all the forms the value gets erased. How do I declare it so I can use it continuously in all three forms.Growl
A
2

App.xaml:

<Application x:Class="WpfTutorialSamples.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:sys="clr-namespace:System;assembly=mscorlib"
         StartupUri="WPF application/ResourcesFromCodeBehindSample.xaml">
<Application.Resources>
    <sys:String x:Key="strApp">Hello, Application world!</sys:String>
</Application.Resources>

Code-behind:

Application.Current.FindResource("strApp").ToString()
Alkahest answered 22/12, 2014 at 0:8 Comment(0)
M
0

Hi there's essentially two main ways to use the Properties like global access in whole your project. static properties and non static properties.

For the first way you can declare a class global inside your project:

public class Global
  {
      /// <summary>
      /// Gets the Current application
      /// </summary>
      public static string Test {get; set;};
  }

and use this property inside your project where you want like this way:

 public class testClass1
 {
    public MethodTest1()
    {
      var test1 = Global.Test;
      Global.Test = test1 + "add1";
    }
 }



 public class testClass2
     {
        public MethodTest2()
        {
          var test2 = Global.Test;
          Global.Test = test2 + "add2";
        }
     }

the final value of Test is "add1add2"

But if you wants use the other way without create a class you can use the class App from App.xaml.cs in this way:

public partial class App
{
   private string? test = default;
   public string Test { get => test; set => test=value; }
}

and use it around your project in this way:

public class testClass1
     {
        public MethodTest1()
        {
          var test1 = Application.Current.Test;
          Application.Current.Test = test1 + "add1";
        }
     }

   

     public class testClass2
         {
            public MethodTest2()
            {
              var test2 = Application.Current.Test;
              Application.Current.Test = test2 + "add2";
            }
         }

the final value is the same like the previous example

Monagan answered 26/1, 2024 at 15:38 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.