简体   繁体   English

私人方法问题C#(从工具条菜单项更改颜色)

[英]private method issue c# (change color from tool strip menu item)

I have a logic issue on a tic tac toe game. 我在井字游戏中遇到逻辑问题。 I want to add a new feature. 我想添加一个新功能。 When I click on "Yellow Color" in the menu, I want my red cross to become yellow when the cursor enters the button. 当我单击菜单中的“黄色”时,当光标进入按钮时,我希望我的红叉变成黄色。

I can't see the variable "b" from the following method, so I was wondering how should I do that. 我无法从以下方法中看到变量“ b”,所以我想知道应该怎么做。

private void yellowColorToolStripMenuItem_Click(object sender, EventArgs e)
{
    b.ForeColor= System.Drawing.Color.Yellow;
} //syntax error

private void button_enter(object sender, EventArgs e)
{
    Button b = (Button)sender;
    if (b.Enabled)
    {
        if (turn)
        {
            b.ForeColor = System.Drawing.Color.Red;
            b.Text = "X";
        }
        else
        {
            b.ForeColor = System.Drawing.Color.Blue;
            b.Text = "O";
        }
    }
}

I couldn't find anything on the net 我在网上找不到任何东西

You've declared a local variable in the button_enter method. 您已经在button_enter方法中声明了局部变量 That variable is only available within the method. 该变量在方法内可用。 If you want that variable to be part of the start of the instance, you need to make it an instance variable, declared outside any method. 如果要让该变量成为实例开始的一部分,则需要使其成为实例变量,并在任何方法外部声明。

However, it sounds like the real state that you want isn't another button reference - it's "the colour to set the foreground to when the cursor enters the button". 但是,听起来像您想要的真实状态不是另一个按钮引用-它是“将光标输入按钮时将前景设置为的颜色”。 So you might have: 所以你可能有:

private Color entryColor;

private void yellowColorToolStripMenuItem_Click(object sender, EventArgs e)
{
    entryColor = Color.Yellow;
}

private void button_enter(object sender, EventArgs e)
{
    Button b = (Button) sender;
    if (b.Enabled)
    {
        if (turn)
        {
            b.ForeColor = entryColor;
            b.Text = "X";
        }
        else
        {
            b.ForeColor = Color.Blue;
            b.Text = "O";
        }
    }
}

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

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