如何将悬停效果添加到TListBoxItem?

时间:2017-03-27 13:32:58

标签: delphi firemonkey

使用其他样式控件,我通常会将自然背景矩形添加到自定义ListboxItem样式并使用Trigger: IsMouseOver=true定义颜色动画,但在这种情况下它不起作用。

仅当我为背景矩形设置HitTest := True时,悬停动画才有效,但ListBox不会响应项目的点击,也无法选择项目。

如何将悬停效果添加到ListBox?

1 个答案:

答案 0 :(得分:1)

我刚才遇到了同样的问题。 我能找到的唯一解决方法是跳过样式并创建自己的listboxitem。唯一的问题是你的文字会消失,所以我添加了一个标签来显示文字。 它不是伟大的,但它在我的情况下工作

type
  TMouseOverListBoxItem = class(TListBoxItem)
  private
    FBackGround: TRectangle;
    FHoverAni: TColorAnimation;
    FLabel: TLabel;
    procedure BackgroundClicked(Sender: TObject);
  protected
    procedure DoTextChanged; override;
  public
    procedure AfterConstruction; override;
 end;


procedure TMouseOverListBoxItem.AfterConstruction;
const 
  cStart = TAlphaColorRec.White;
  cStop  = TAlphaColorRec.Yellow;
begin
  inherited;
  // Create background
  FBackGround := TRectangle.Create(Self);
  FBackGround.Parent := Self;
  FBackGround.Fill.Color := cStart;
  FBackGround.Align := TAlignLayout.Contents;
  FBackGround.HitTest := True;
  FBackGround.Sides := [];
  FBackGround.OnClick := BackgroundClicked;

  // Create mouse over animation
  FHoverAni := TColorAnimation.Create(FBackGround);
  FHoverAni.Parent := FBackGround;
  FHoverAni.Trigger := 'IsMouseOver=true';
  FHoverAni.TriggerInverse := 'IsMouseOver=false';
  FHoverAni.StartValue := cStart;
  FHoverAni.StopValue := cStop;
  FHoverAni.PropertyName := 'Fill.Color';

   // Create label to show text. Background will hide original text
  FLabel := TLabel.Create(FBackGround);
  FLabel.Parent := FBackGround;
  FLabel.Align := TAlignLayout.Client;
end;

procedure TMouseOverListBoxItem.BackgroundClicked(Sender: TObject);
begin
  if Assigned(OnClick) then
    OnClick(Self)
  else if Assigned(ListBox.OnItemClick) then
    ListBox.OnItemClick(ListBox, Self);
end;

procedure TMouseOverListBoxItem.DoTextChanged;
begin
  inherited;
  FLabel.Text := Self.Text;
end;
相关问题