WPF Application using a global variable

前端 未结 6 2026
余生分开走
余生分开走 2020-12-08 11:10

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

6条回答
  •  失恋的感觉
    2020-12-08 11:48

    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();
    

    On a side note, do notice that using the static class as global variables in c# is considered a bad practice (that's why there is no official implementation for globals), but I consider it a shortcut for when I am too lazy haha. It should not be used in the professional environment.

提交回复
热议问题