Grouping Controls

放肆的年华 提交于 2019-12-11 04:52:10

问题


I'm using C++ Builder 5. Is there a way to group a disparate set of controls so that by simply calling, for instance, myGroup.Enabled = false; will set all group of controls enabled property to false? I can't use a GroupBox since the controls (labels, checkboxes, etc) are on different TabPages.

The reason I ask is so I don't have to call each control's enabled property explicitly and can do it with one simple call.

If not, how can I create a custom Control class to do this?


回答1:


You could use the Tag property of the controls and create your own grouping.

void TForm1::SetControlState(TWinControl *WinCtrl, const bool IsEnabled, const int TagValue)
{
 // set the enabled property for each control with matching TagValue
 for (int Index = 0; Index < WinCtrl->ControlCount; ++Index)
 {
   if (WinCtrl->Controls[Index]->Tag == TagValue)
   {
     WinCtrl->Controls[Index]->Enabled = IsEnabled;
   }

   // set child controls
   if (WinCtrl->Controls[Index]->InheritsFrom(__classid(TWinControl)))
   {
     TWinControl *TempWinCtrl;
     TempWinCtrl = static_cast<TWinControl *>(WinCtrl->Controls[Index]);
     SetControlState(TempWinCtrl, IsEnabled, TagValue);
   }
 } // end for
}

Alternatively, If you want to enable/disable all controls in one go.

void TForm1::SetControlState(TWinControl *WinCtrl, const bool IsEnabled)
{
 // set the enabled property for each control with parent TabSheet
 for (int Index = 0; Index < WinCtrl->ControlCount; ++Index)
 {
   WinCtrl->Controls[Index]->Enabled = IsEnabled;

   // disable child controls
   if (WinCtrl->Controls[Index]->InheritsFrom(__classid(TWinControl)))
   {
     TWinControl *TempWinCtrl;
     TempWinCtrl = static_cast<TWinControl *>(WinCtrl->Controls[Index]);
     SetControlState(TempWinCtrl, IsEnabled);
   }
 } // end for
} 

Examples:

// disable all controls on the form
SetControlState(Form1, false);

// disable all controls on a tabsheet
SetControlState(TabSheet1, false);

NOTE: The above code has been tested with C++Builder 2007




回答2:


Since the controls you want to group are not in the same container, then I suggest using a TAction (look at the TActionList component). All TControl descendants have a public (sometimes even published) Action property. You can have the same TAction object assigned to multiple controls at the same time. Enabling/disabling the TAction (or updating any of its other properties) will automatically update all associated controls accordingly.



来源:https://stackoverflow.com/questions/1986392/grouping-controls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!