MammouthQc
MammouthQc

Reputation: 7

Checkbox coloring

I'm new to C#. I've developed a small program that is similar to Hangman... Here is my issue : I can't find any working commands that will change the color of my Check-box.

Here is the code of my program [The actual code is working where the comments are is where I want to understand how to change the colors of the Check-box] :

        public void voirSiLettre(char lettre)
    {
        if (motRechercher.Contains(lettre))
        {
            for (int i = 0; i < motRechercher.Length; i++)
            {
                if (motRechercher[i].Equals(lettre))
                {
                    StringBuilder sb = new StringBuilder(txtMot.Text);
                    sb[i] = lettre;
                    txtMot.Text = sb.ToString();
                }
            } //CheckBox --> Green
        }
        else
        {
            //CheckBox --> Red
        }
    }

Here is the code of a Check-box incase you wanted it :

    private void chkA_Checked(object sender, RoutedEventArgs e)
    {
        voirSiLettre('a');
        chkA.IsEnabled = false;
    }

It's pretty simple but I can't find the good commands and/or how to place it in this code. I am not asking for a code, maybe just a command with some explanation; I am here to learn.

Upvotes: 0

Views: 1712

Answers (1)

DaveGreen
DaveGreen

Reputation: 405

To change the background colour of a checkbox you can use Checkbox.Background = Brush, in your case it would be

chkA.Background = new SolidColorBrush(Colors.Red);

This works fine if you are dealing with the checkbox without it changing state, however if you set it to green and then the user checks the box, it will stay green unless you handle the change in your checked event.

The other alternative is to look at adding a style in your xaml such as:

<Window.Resources>
    <Style TargetType="CheckBox" x:Name="test">
        <Setter Property="Background" Value="Green"/>
    </Style>
</Window.Resources>

You could then use that as the normal background and modify it in code when you wanted to change it to red.

Upvotes: 1

Related Questions