简体   繁体   English

C#根据跟踪栏值更改标签的颜色

[英]C# Changing color of label based on trackbar value

I am working with a trackbar that has a value of 0 to 100. In my code automatic = 0 that you see in the image below. 我正在使用一个值为0到100的轨迹栏。在我的代码中automatic = 0,如下图所示。

What i am trying to accomplish is that any number below 35 should change the labels (lableFS) forcolor to red, while any number above that should change the labels forecolor to green. 我要完成的工作是,任何低于35的数字都应将前颜色的标签(lableFS)更改为红色,而任何高于35的数字都应将前颜色的标签更改为绿色。 I have that working fine, however the exception here should be that if the value of the trackbar is 0 or even if the labelFS text is set to "Automatic", then the labelFS forecolor should be black. 我的工作正常,但是这里的例外应该是,如果轨迹栏的值为0或即使labelFS文本设置为“自动”,那么labelFS的前景色应为黑色。 Below is a gif image that will show you exactly what i mean, as well as my current code. 下面是一张gif图片,它将准确显示我的意思以及当前的代码。

Thank you in advance for any help! 预先感谢您的任何帮助!

演示我的应用

I know its a simple issue, however i have tried numerous ways and i cant seem to find what is stopping it from changing to black. 我知道这是一个简单的问题,但是我尝试了许多方法,但似乎无法找到阻止它变黑的原因。

        private void fanSlider_Scroll(object sender, EventArgs e)
    {
        lblFS.Text = "" + fanSlider.Value * 5;

        if (lblFS.Text == "0")
        {
            lblFS.Text = "Automatic";
        }

        int value;
        if (Int32.TryParse(lblFS.Text, out value))
        {
            if (value <= 35)
            {
                lblFS.ForeColor = System.Drawing.Color.Red;
            }
            if (value > 35)
            {
                lblFS.ForeColor = System.Drawing.Color.Green;

            }

            if (value == 0)
            {
                lblFS.ForeColor = System.Drawing.Color.Black;
            }
        }


    }

I think what is happening here is that whenever the bar is at 0 you set its text to Automatic , and then afterwards you try to change its color checking if its text is 0 but since you have already changed it to Automatic the condition will always be false... 我认为这里发生的事情是,每当条形为0时,您都将其文本设置为Automatic ,然后尝试更改其颜色,以检查其文本是否为0,但是由于您已经将其更改为Automatic因此条件始终为假...

Try this: 尝试这个:

private void fanSlider_Scroll(object sender, EventArgs e)
{
    lblFS.Text = "" + fanSlider.Value * 5;
    if (lblFS.Text == "0")
    {
        lblFS.Text = "Automatic";
        lblFS.ForeColor = System.Drawing.Color.Black;
    }
    int value;
    if (Int32.TryParse(lblFS.Text, out value))
    {
        if (value <= 35)
        {
            lblFS.ForeColor = System.Drawing.Color.Red;
        }
        if (value > 35)
        {
            lblFS.ForeColor = System.Drawing.Color.Green;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM