Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to attach an object of any type with a TControl?

I want to add a TList with a TTreeViewItem and a custom class (TRoom)'s object with another. In delphi 2007 there was a field 'Data' of Pointer type which has been replaced with a TValue here which I don't know as to how to use. I have searched the internet with some stating that it can't handle custom types for the time being.

Can somebody devise a way to achieve this, except for making a hack class?

For example, the following form code should run properly:-

unit Unit1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes,
  System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs,
  FMX.TreeView, FMX.Layouts, FMX.Edit;

type
  TRoom = class

    ID : WORD;
    Name : String;

  end;

  TForm1 = class(TForm)
    TreeView1: TTreeView;
    TreeViewItem1: TTreeViewItem;
    Button1: TButton;
    Edit1: TEdit;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.fmx}

procedure TForm1.Button1Click(Sender: TObject);
var
  List : TList;
begin

  // Get The List From TreeViewItem1
  // pani's Solution  - List := TList ( TreeViewItem1.TagObject );

  Edit1.Text := TRoom ( List.First ).Name;

end;

procedure TForm1.FormCreate(Sender: TObject);
var
  Room : TRoom;
  List : TList;

begin

  List := TList.Create;
  Room := TRoom.Create;
  Room.ID := 5;
  Room.Name := IntToStr ( 5 );
  List.Add ( Room );

  // Add The List To TreeViewItem1    
  // pani's Solution  - TreeViewItem1.TagObject := List;

end;

end.
like image 674
Umair Ahmed Avatar asked Oct 02 '22 08:10

Umair Ahmed


1 Answers

If you want to "attach" an object to TControl, TControl's parent class TFmxObject introduces the .TagObject property that stores any object value.

Besides using this property you can also use the .Tag property with typecasting into NativeInt and your wanted class type, for example: TreeViewItem1.Tag := NativeInt(List); and List := TList(TreeViewItem1.Tag);

like image 122
pani Avatar answered Oct 13 '22 10:10

pani