有没有办法获取容器控件上的所有控件? [英] Is there any way to get all the controls on a container control?

查看:188
本文介绍了有没有办法获取容器控件上的所有控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单上有一堆控件,我想在某个面板上遍历所有控件,并启用/禁用它们。

I've got a form with a bunch of controls on it, and I wanted to iterate through all the controls on a certain panel and enable/disable them.

我试过这个:

var component: TComponent;
begin
  for component in myPanel do
    (component as TControl).Enabled := Value;
end;

但这没有做。原来所有组件都在窗体的组件集合中,而不是它们的父对象。所以有人知道是否有任何方法可以控制所有的控件? (除了一个丑陋的解决方案,这是我最后必须做的):

But that did nothing. Turns out all components are in the form's component collection, not their parent object's. So does anyone know if there's any way to get all the controls inside a control? (Besides an ugly workaround like this, which is what I ended up having to do):

var component: TComponent;
begin
  for component in myPanel do
    if (component is TControl) and (TControl(component).parent = myPanel) then
      TControl(component).Enabled := Value;
end;

有人请告诉我有更好的方法...

Someone please tell me there's a better way...

推荐答案

您正在寻找 TWinControl.Controls 数组和随附的 ControlCount 属性。那些是控制的直系子女。要获得孙子等等,请使用标准递归技术。

You're looking for the TWinControl.Controls array and the accompanying ControlCount property. Those are for a control's immediate children. To get grandchildren etc., use standard recursive techniques.

您不希望组件数组是中在循环中的循环遍历),因为一般而言,小孩关系组件可以拥有没有孩子关系的东西,控件可以拥有他们不拥有的子项。

You don't really want the Components array (which is what the for-in loop iterates over) since it has nothing to do, in general, with the parent-child relationship. Components can own things that have no child relationship, and controls can have children that they don't own.

还要注意,禁用控件也会隐式地禁用其所有子项。你不能与残疾人控制的孩子互动;操作系统不会向其发送输入消息。为了让他们看起来禁用,但是您需要单独禁用它们。也就是说,为了使一个按钮有灰色的文本,这不足以禁用其父级,即使该按钮不会响应鼠标点击。您需要禁用按钮本身,使其自身被禁用。

Also note that disabling a control implicitly disables all its children, too. You cannot interact with the children of a disabled control; the OS doesn't send input messages to them. To make them look disabled, though, you'll need to disable them separately. That is, to make a button have grayed text, it's not enough to disable its parent, even though the button won't respond to mouse clicks. You need to disable the button itself to make it paint itself "disabledly."

这篇关于有没有办法获取容器控件上的所有控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆