按标题搜索标签 [英] Search for a Label by its Caption

查看:78
本文介绍了按标题搜索标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何通过 Caption 搜索标签:

I was trying to figure out how to search for a Label by its Caption:

for I := ComponentCount - 1 downto 0 do
begin
  if Components[i] is TLabel then
    if Components[i].Caption = mnNumber then
    begin
      Components[i].Left := Left;
      Components[i].Top := Top + 8;
    end;
end;

我收到错误:未声明的标识符:'Caption'

我如何解决这个问题?

I get an error: Undeclared identifier: 'Caption'.
How can I resolve this issue?

推荐答案

最后的信息落入将您的评论放在Golez的答案中:您的标签是在运行时创建的,所以有机会没有将 Form 作为所有者。您将需要使用 Controls [] 数组来查看表单中所有父控件的所有控件,并递归地显示所有 TWinControl 后代,因为它们也可能包含 TLabel

The final piece of information fell into place in your comment to Golez's answer: your Labels are created at run-time, so there's a chance they don't have the Form as an owner. You'll need to use the Controls[] array to look at all the controls that are parented by the form, and look recursively into all TWinControl descendants because they might also contain TLabel's.

如果你要做这个分配和不同类型的控件,你可能想要实现某种帮助,所以你不要经常重复。看看大卫的答案是一个现成的解决方案,设法包含一些钟声和口哨,超出了解决手头的问题;就像使用匿名函数来操作找到的控件的能力一样,它的能力使用匿名函数来根据任何条件过滤控件。

If you're going to do this allot and for different types of controls, you'll probably want to implement some sort of helper so you don't repeat yourself too often. Look at David's answer for a ready-made solution that manages to include some "bells and whistles", beyond solving the problem at hand; Like the ability to use anonymous functions to manipulate the found controls, and it's ability use an anonymous function to filter controls based on any criteria.

在开始使用这样一个复杂的解决方案,你应该可以理解最简单的一个。一个非常简单的递归函数,简单地查看从表单开始的所有容器上的所有 TControls 。如下所示:

Before you start using such a complicated solution, you should probably understand the simplest one. A very simple recursive function that simply looks at all TControls on all containers starting from the form. Something like this:

procedure TForm1.Button1Click(Sender: TObject);

  procedure RecursiveSearchForLabels(const P: TWinControl);
  var i:Integer;
  begin
    for i:=0 to P.ControlCount-1 do
      if P.Controls[i] is TWinControl then
        RecursiveSearchForLabels(TWinControl(P.Controls[i]))
      else if P.Controls[i] is TLabel then
        TLabel(P.Controls[i]).Caption := 'Test';
  end;

begin
  RecursiveSearchForLables(Self);
end;

使用David的通用代码,上述可以重写为:

Using David's generic code, the above could be re-written as:

procedure TForm1.Button1Click(Sender: TObject);
begin
  TControls.WalkControls<TLabel>(Self, nil,
    procedure(lbl: TLabel)
    begin
      lbl.Caption := 'Test';
    end
  );
end;

这篇关于按标题搜索标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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