单击时将按钮的文本从“打开”切换为“关闭”(Visual C ++)

时间:2012-07-20 09:43:36

标签: c++ visual-c++

正如你们中的一些人可能已经知道的那样(从我最近的问题),我已经开始学习C ++了。因此,我很可能会问一些非常微不足道的问题,所以如果这个问题太微不足道,请跟我一起来......

当我点击它时,我只给了一个简单的按钮的文本切换“开”和“关”的小任务 - 它已经从文本“关闭”开始,因为它还没有按下,但当你单击它更改为“开”。在之后的每次交替点击中,按钮的文本理想地保持从“开”变为“关”。在我的情况下,我认为一个简单的布尔变量将是解决方案,因为On和Off可以被视为True或False,但不是......

无论如何,这是我到目前为止所拥有的按钮处理程序的代码:

private: System::Void toggleButtonText_Click(System::Object^  sender, System::EventArgs^  e) 
    {
      static bool isOn = true;
      if(isOn == false)
      {
       toggleButtonText->Text = "Off";

      }
      else
      {
      toggleButtonText->Text = "On";
      }

}

如您所见,按钮的名称是“toggleButtonText”。在InitializeComponent(void)方法中,此行启用默认文本“Off”:

this->toggleButtonText->Text = L"On";

看看我的其余任务,做到这一点会给我足够的线索,让我自己尝试,而不是花费数年时间无休止的谷歌搜索。任何帮助将非常感谢:)。

3 个答案:

答案 0 :(得分:3)

每次单击按钮时都需要切换标记。如果您使用?:运算符,也可以大大减小代码的大小:

static bool isOn = true;
toggleButtonText->Text = isOn ? "On" : "Off";
isOn = !isOn;

答案 1 :(得分:1)

切换文本后,您必须更新变量状态

  static bool isOn = true;
  if(isOn == false)
  {
     toggleButtonText->Text = "Off";
  }
  else
  {
     toggleButtonText->Text = "On";
  }
  isOn = !isOn; //toggle the flag too

答案 2 :(得分:1)

在这里使用静态变量是一个非常糟糕的解决方案。例如,如果以编程方式更改按钮的状态,则静态变量将与实际按下状态不同步。

为什么不从按钮本身获得切换状态? Here's anwser how to add actual toggle button in the Windows Forms.之后,您可以通过以下方式修改方法:

System::Void toggleButtonText_Click(System::Object^  sender, System::EventArgs^  e) 
{
    CheckBox^ button = (CheckBox^)sender;
    if (button->Checked)
    {
        button->Text = "On";
    }
    else
    {
        button->Text = "Off";
    }
}