I'm still new to c# and been playing around a bit, for my project I have these two forms, on form 1 I have these variables
Color ColCurrentPrimary = Color.FromArgb(35, 39, 42);
Color ColCurrentSecondary = Color.FromArgb(44, 47, 51);
On form 2
I have a window dialog, and this should keep the same theme
eg:
this.BackColor = ColCurrentPrimary;
this.ForeColor = ColCurrentSecondary;
However, ColCurrent Primary and secondary don't exist on Form 2, how would I go about passing them? or is there a "Global" that can be accessed from both forms?
any advice would be much appreciated,
thank you for reading,
Samuel
A solution that would work very well for you would be a Singleton . Read through that page - it will tell you everything you need to know about creating one. Once you have it, you can initialize it's properties from either a config file or just set them in code - then the class can be used globally to configure any new forms.
This is what I usually use:
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
//add public properties here to use for your config!
public Color ColCurrentPrimary { get; set; }
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Then you can use it like this:
Singleton.Instance.ColCurrentPrimary
As Steve has mentioned, you could use a static class also. That may be simpler for your case. Singletons are great for multi threaded applications but may be a little overkill for this. Here is an example of a static class:
static class Config
{
public static Color ColCurrentPrimary { get; set; }
}
Then you can use it like this:
Config.ColCurrentPrimary
You just have to make sure that you define the class in a namespace that you will have access to where you need to access it, or add a using
statement to make it accessible.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.