0

I would like to create a variable which uses another variable outside of a function, like this:

private void tb_TextChanged(object sender, TextChangedEventArgs e)
{
  ...
}

TextStyle txtstyle = new TextStyle(new SolidBrush(Color.Red), null, FontStyle.Regular); // the variable

private void tb_VisibleRangeChangedDelayed(object sender, EventArgs e)
{
  ...
}

I want to replace Color.Red in txtstyle with a custom color which is in the applications setting. How can I achieve this?

3
  • 1
    Why do you want it done this way? Can you not declare the variable and initialize it in a constructor with the values you want? Commented Oct 24, 2011 at 13:46
  • Why you've provided two methods? You want to change text style once or in each function call? Commented Oct 24, 2011 at 13:46
  • I just provided the methods to show that the variable is outside of them. Commented Oct 28, 2011 at 7:26

3 Answers 3

4

I would create a private property like this:

private TextStyle myTextStyle
    {
        get
        {
            var colorName = "Red";

            if(!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["myColor"]))
            {
                colorName = ConfigurationManager.AppSettings["myColor"];
            }

            return new TextStyle(new SolidBrush(Color.FromName(colorName)), null, FontStyle.Regular);
        }
    }

you have to add a reference to System.Configuration for this to work.

Sign up to request clarification or add additional context in comments.

2 Comments

Took me awhile to fully understand his question as asked, but from what I could figure out, this is exactly what he's looking for.
Yes, however since the code posted by Fischermaen is more shorter, I have used his one instead.
2

Since you have declared txtstyle in the class scope, you can access it from within functions that are part of the same class.

I suggest you read up on C# scoping rules.

3 Comments

I want to replace Color.Red in txtstyle ... seems to be missing
I thought he is asking as how to replace the Color from the App settings
@V4Vendetta - That's not my reading. My understanding is that the Color is initialized from config, but he then wants to change it during runtime, not to change the config.
1

You can access the settings in this way:

TextStyle txtstyle = new TextStyle(new SolidBrush(Properties.Settings.Default["Color"]), null, FontStyle.Regular); // the variable 

1 Comment

Exactly what I wanted, and it's very simple too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.