Lemons
Lemons

Reputation: 19

Would like to add different themes to my application

Basically, I'm making a basic note taking app and would like to add different color options, for an example, a light version and dark version for easier viewing by the user. I plan to give it to a few friends but no one can agree on a color so I thought I'd just make it customizeable by the user via small buttons.

I'm not very experienced however and was wondering how I'd go about doing this?

Upvotes: 1

Views: 526

Answers (1)

John Doe
John Doe

Reputation: 374

You could loop through all the controls and change their .BackColor:

private void ChangeTheme_btn_Click(object sender, EventArgs e)
{
    ChangeTheme(this.Controls, Color.Aqua);
}

private void ChangeTheme(Control.ControlCollection controls, Color color)
{
    foreach (Control control in controls)
    {
        if (control.HasChildren)
        {
            // Recursively loop through the child controls
            ChangeTheme(control.Controls, color);
        }
        else
        {
            if (control is TextBox textBox)
            {
                textBox.BackColor = color;
            }
            else if (control is Button button)
            {
                button.BackColor = color;
            }
        }
    }
}

You could set a separate color to each type of control, and also change other properties.

If you have multiple forms, you can do:

private readonly List<Control> listOfAllFormControls = new List<Control>();
private void MyForm1_form_Load(object sender, EventArgs e)
{
    // Add all the controls to the list
    foreach (Control item in MyForm1.instance.Controls)
    {
        listOfAllFormControls.Add(item);
    }
    foreach (Control item in MyForm2.instance.Controls)
    {
        listOfAllFormControls.Add(item);
    }
}

private void ChangeTheme_btn_Click(object sender, EventArgs e)
{
    SetColorThemeToLight(listOfAllFormControls);
}



private void SetColorThemeToLight(List<Control> list)
{
    foreach (Control control in list)
    {
        if (control.HasChildren)
        {
            // Recursively loop through the child controls
            List<Control> controlList = new List<Control>();
            foreach (Control item in control.Controls)
            {
                controlList.Add(item);
            }
            SetColorThemeToLight(controlList);
        }
        else
        {
            switch (control)
            {
                case TextBox textBox:
                    textBox.BackColor = Color.Blue;
                    break;

                case Button button:
                    button.BackColor = Color.Blue;
                    break;
            }
        }
    }
}

I also used a switch case instead

Upvotes: 2

Related Questions