使用ComboBox在TImage中加载ImageList图片

Alb*_*ola 4 delphi

在我的Delphi表单中,我有一个包含4张图片的ImageList.还有一个被调用的ComboBox ComboBox1和一个被调用的TImage组件Image9.

onChange为我的ComboBox 创建了一个,因为我想做这样的事情:如果选择了ComboBox项目1,则在我的ImageList中加载图像1.如果选择了ComboBox项目3(例如),则加载ImageList的图像3.

我写的代码是这样的:

case ComboBox1.Items[ComboBox1.ItemIndex] of
0:
 begin
  ImageList1.GetBitmap(0,Image9.Picture);
 end;
1:
 begin
  ImageList1.GetBitmap(1,Image9.Picture);
 end;
2:
 begin
  ImageList1.GetBitmap(2,Image9.Picture);
 end;
3:
 begin
  ImageList1.GetBitmap(3,Image9.Picture);
 end;
end;
Run Code Online (Sandbox Code Playgroud)

使用此代码,IDE(我正在使用Delphi XE4)给我一个错误,case ComboBox1.Items[ComboBox1.ItemIndex] of因为它表示需要Ordinal类型.我能做什么?

Ken*_*ite 9

caseDelphi中的语句适用于Ordinal类型:

序数类型包括整数,字符,布尔值,枚举和子范围类型.序数类型定义了一组有序的值,其中除第一个值之外的每个值都具有唯一的前任,并且除了最后一个值之外的每个值都具有唯一的后继值.此外,每个值都有一个标准,它决定了类型的顺序.在大多数情况下,如果一个值具有n次幂,则其前身具有n-1的正常性,其后继者具有n + 1的正常性

ComboBox.Items 是字符串,因此不符合作为序数的要求.

另外,如下面的评论中所述,您不能Image9.Picture直接分配给您; 你必须Image9.Picture.Bitmap改用.为了TImage正确更新以反映更改,您需要调用它的Invalidate方法.)

改变你的case使用ItemIndex,而不是直接:

case ComboBox1.ItemIndex of
  0: ImageList1.GetBitmap(0,Image9.Picture.Bitmap);
  1: ImageList1.GetBitmap(1,Image9.Picture.Bitmap);
end;
Image9.Invalidate;  // Refresh image
Run Code Online (Sandbox Code Playgroud)

或者直接去 ImageList

if ComboBox1.ItemIndex <> -1 then
begin
  ImageList1.GetBitmap(ComboBox1.ItemIndex, Image9.Picture.Bitmap);
  Image9.Invalidate;
end;
Run Code Online (Sandbox Code Playgroud)

  • @ DK64:谢谢你的信息; 我没有仔细研究那部分代码.我已经添加了作为未来读者的注释,并更新了代码以反映这一点.感谢upvote并接受.:-) (2认同)