【问题标题】:How to get fmx listbox.ScrollToItem to work on form creation or activation如何让 fmx listbox.ScrollToItem 用于创建或激活表单
【发布时间】:2021-10-06 09:23:20
【问题描述】:

我在 onCreate 事件中填充了一个带有 at TListBox 的表单,我还在那里设置了所选项目。 我希望列表框在表单显示时显示所选项目,因此我尝试触发 ScrollToItem 方法。这不起作用。我也尝试将它放在OnShowOnActivate 事件中,但它仍然不起作用。有没有办法让它工作? 这是一个说明问题的示例程序:

`type
  TForm5 = class(TForm)
    ListBox1: TListBox;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form5: TForm5;

implementation

{$R *.fmx}

procedure TForm5.FormCreate(Sender: TObject);
var
  i: Integer;
  lbi: TListBoxItem;
begin
 for i := 1 to 50 do
 begin
    lbi := TListBoxItem.Create(ListBox1);
    lbi.Text := 'item ' + inttostr(i);
    ListBox1.AddObject( lbi );
 end;
  ListBox1.itemindex := ListBox1.items.indexof('item 48');
  ListBox1.ScrollToItem(ListBox1.Selected);
end;

end.`

和 FMX 文件:

`object Form5: TForm5
  Left = 0
  Top = 0
  Caption = 'Form5'
  ClientHeight = 480
  ClientWidth = 640
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [Desktop]
  OnCreate = FormCreate
  DesignerMasterStyle = 0
  object ListBox1: TListBox
    Position.X = 224.000000000000000000
    Position.Y = 144.000000000000000000
    TabOrder = 1
    DisableFocusEffect = True
    DefaultItemStyles.ItemStyle = ''
    DefaultItemStyles.GroupHeaderStyle = ''
    DefaultItemStyles.GroupFooterStyle = ''
    Viewport.Width = 196.000000000000000000
    Viewport.Height = 196.000000000000000000
  end
end`

【问题讨论】:

    标签: delphi scroll firemonkey tlistbox


    【解决方案1】:

    TListBox 有一个属性ViewportPosition: TPointF 来设置滚动条。设置ListBox1.ItemIndex后添加以下行:

    ListBox1.ViewportPosition := PointF(0.0, ListBox1.itemindex * ListBox1.ItemHeight);
    

    前面假设所有项目都具有相同的高度(TListBox1.ItemHeight 在 Object Inspector 或更早的代码中设置)。您的 FMX 文件没有反映这一点,因此您可能需要添加它,否则滚动将不会发生。

    您可能希望为项目设置单独的高度。在这种情况下,您必须遍历所有项目,直到您想要被选中的项目,并将它们的高度相加,以获得 ViewportPositionY 术语。

    【讨论】:

    • 好吧,有点。 Itemheight 默认设置为 0,因此,正如您所说,滚动不起作用。我不得不任意选择一个 itemheight 并在 IDE 中设置它。我将它设置为 20,它现在滚动到所选项目,该项目出现在可见列表框的后半部分。我认为这不是一个非常优雅的解决方案,但我可以使用它。感谢您的帮助。
    猜你喜欢
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 2017-11-11
    • 1970-01-01
    • 2020-05-29
    • 2014-12-20
    • 2014-05-14
    相关资源
    最近更新 更多