locked
Scope of Public variables declared at top of Application Class RRS feed

  • Question

  • Hi,

    I'd like to know why a Public variable declared in WPF application (in VB) does not appear to be accessible from the code running in the MainWindow class and how do you share limited data between these classes?

    Part of my Application reads configuration data from a text file.  The configuration data is then stored in a Public Array in the Application Class to be used by the MainWindow code to adjust the position of Objects on the screen based on the default layout contained in the MainWindow XAML file.

    What's the best coding practise to achieve this type of requirement?

    Thanks!

    Wednesday, February 21, 2018 2:02 PM

Answers

  • Hi, I couldn't find any detail about creating singleton in VB.  I also read somewhere that VB does not support a Static Class. I therefore decided to simply add a Module in VB where I could declare just the Configuration arrays I needed as Public with a global scope to the Application and MainWindow which seems to work. Thanks!

    • Marked as answer by LH63 Wednesday, February 21, 2018 11:01 PM
    Wednesday, February 21, 2018 11:01 PM

All replies

  • If you are adding properties or methods to the App class then you can access that from a window by using:

    var x = (App) Application.Current).MyProperty;


    However, I would recommend that you instead use a static class to represent some kind of global config. E.g

    public static class MyConfig
        {
            static MyConfig()
            {
                // Static constructor. Do some initialisation here
            }
    
            public static string SomeProperty { get; set; }
        }


    Or, probably better, by using the singleton pattern.

    Edtit: Probably should point out my examples are in C#, but the same principles should apply to VB

    • Edited by RJP1973 Wednesday, February 21, 2018 2:27 PM
    Wednesday, February 21, 2018 2:20 PM
  • Hi, I couldn't find any detail about creating singleton in VB.  I also read somewhere that VB does not support a Static Class. I therefore decided to simply add a Module in VB where I could declare just the Configuration arrays I needed as Public with a global scope to the Application and MainWindow which seems to work. Thanks!

    • Marked as answer by LH63 Wednesday, February 21, 2018 11:01 PM
    Wednesday, February 21, 2018 11:01 PM