如何获取有对象的页面编号?例如:第一页有Button1,第二页有Button2,请问有Button1而没有ActivePageIndex,如何获取页面编号?谢谢。
问问题
654 次
5 回答
7
想要找到一个特定类的最近的父类是很常见的。因此,创建一个功能来做到这一点是有好处的。
function GetParentWithClass(Control: TControl;
ClassType: TWinControlClass): TWinControl;
begin
Result := Control.Parent;
while Assigned(Result) and not (Result is ClassType) do
Result := Result.Parent;
end;
一旦你有了这个,你就可以用它来解决你当前的问题。
var
PageIndex: Integer;
TabSheet: TTabSheet;
.....
TabSheet := GetParentWithClass(Control, TTabSheet) as TTabSheet;
PageIndex := TabSheet.PageIndex;
将这样的问题分开后,您可以GetParentWithClass
在其他设置中使用。
于 2013-01-11T09:48:28.957 回答
2
我喜欢Generics
用以避免重复
PageIndex := TComponentUtil.GetParent<TTabSheet>( MyControl ).PageIndex;
有这样的课
unit ComponentUtils;
interface
uses
Classes, Controls;
type
TComponentUtil = class abstract
class function GetOwner<T : TComponent>( AComponent : TComponent ) : T;
class function GetParent<T : TWinControl>( AControl : TControl ) : T;
end;
implementation
{ TComponentUtil }
class function TComponentUtil.GetOwner<T>( AComponent : TComponent ) : T;
var
LOwner : TComponent;
begin
LOwner := AComponent.Owner;
while Assigned( LOwner ) and not ( LOwner is T ) do
LOwner := LOwner.Owner;
Result := T( LOwner );
end;
class function TComponentUtil.GetParent<T>( AControl : TControl ) : T;
var
LParent : TWinControl;
begin
LParent := AControl.Parent;
while Assigned( LParent ) and not ( LParent is T ) do
LParent := LParent.Parent;
Result := T( LParent );
end;
end.
于 2013-01-11T11:48:10.820 回答
2
Function GetPageIndexOfControl(c:TControl):Integer;
begin
Result := -1;
While Assigned(c.Parent) and not (c is TTabsheet) do c := c.Parent;
if Assigned(c) then
if c is TTabsheet then
Result := TTabsheet(c).PageIndex;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Showmessage(IntToStr(GetPageIndexOfControl(Button1)));
end;
于 2013-01-11T09:28:41.040 回答
2
尝试这个:
procedure TForm1.Button1Click(Sender: TObject);
begin
if Button1.Parent is TTabSheet then
ShowMessage(IntToStr(TTabSheet(Button1.Parent).PageIndex));
end;
如果按钮直接位于选项卡表中(没有面板或其他控件),则它可以工作。如果您有面板,则可以遍历父链以查看父链是否为 TTabSheet:
procedure TForm1.Button1Click(Sender: TObject);
var
Ctrl: TWinControl;
begin
Ctrl := Button1.Parent;
while Assigned(Ctrl) do
begin
if Ctrl is TTabSheet then
begin
ShowMessage(IntToStr(TTabSheet(Ctrl).PageIndex));
Break;
end
else
Ctrl := Ctrl.Parent;
end;
end;
于 2013-01-11T09:28:59.743 回答
1
至于这里显示的添加没有被问到,我将添加另一个答案
Function GetPageIndexOfControl(c:TControl;var PageControl:TPageControl):Integer;
begin
Result := -1;
While Assigned(c.Parent) and not (c is TTabsheet) do c := c.Parent;
if Assigned(c) then
if c is TTabsheet then
begin
Result := TTabsheet(c).PageIndex;
PageControl := TTabsheet(c).PageControl;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
pc:TPageControl;
i:Integer;
begin
I := GetPageIndexOfControl(Button1,PC);
if (i>-1) and Assigned(PC) then
begin
PC.ActivePageIndex := i;
if Assigned(PC.OnChange) then PC.OnChange(PC);
end;
end;
于 2013-01-11T09:49:39.657 回答