Delphi中的Combobox Style'csDropDownList'

时间:2011-08-23 09:39:22

标签: delphi combobox delphi-7

我在delphi 7中创建了一个表单,并在其上添加了一个组合框。组合框包含项目列表。我不希望用户可以输入值到Combobox,所以我已经设置

combobox.style := csDropDownList;

但是我希望使用combobox.text := 'New Item';代码,但它不起作用。请注意,我想要显示的文本不在项目列表中,我不想在那里添加它。请问有什么解决办法吗?

4 个答案:

答案 0 :(得分:5)

不,这根本不是Windows组合框控件的工作方式。

但是,如果你坚持,并且你不关心你的用户会感到困惑,你可以将Style设置为csDropDown然后再做

procedure TForm1.ComboBox1KeyPress(Sender: TObject; var Key: Char);
begin
  Key := #0;
end;

作为组合框'OnKeyPress事件。然后,用户无法手动输入文本,但只能从列表中的项目中进行选择。但是,仍然可以通过设置Text属性将文本设置为您喜欢的任何内容(即使它不在列表中):

ComboBox1.Text := 'Sample';

答案 1 :(得分:4)

设置ItemIndex属性。如果你还不知道,你可以获得ComboBox.Items.IndexOf('New Item')来获取该文本的索引。

Combobox.ItemIndex := Combobox.Items.IndexOf('New item');

答案 2 :(得分:2)

下面的示例代码演示了如何绘制自定义文本以响应发送到ComboBox控件的父窗口的WM_DRAWITEM消息(这应该是示例的工作表单,否则是子类控件或项目的完整绘图控制是必要的。)

要接收此消息,请将控件的Style属性设置为“csOwnerDrawFixed”,但不要为OnDrawItem事件设置处理程序,以便在我们所有其他情况下应用默认绘图介入绘图。

ItemIndex为-1时,样本会设置文本,但是可以对其进行调整/调整。请注意,绘图代码不完整或准确,样本只是演示了如何完成它的方式:

type
  TForm1 = class(TForm)
    ComboBox1: TComboBox;
    [..]
  private
    procedure WMDrawItem(var Msg: TWMDrawItem); message WM_DRAWITEM;
  end;

[...]

procedure TForm1.WMDrawItem(var Msg: TWMDrawItem);
var
  Font: HFONT;
begin
  inherited;
  if (Msg.Ctl = ComboBox1.Handle) and (Msg.DrawItemStruct.itemID = $FFFFFFFF) and
      ((Msg.DrawItemStruct.itemAction and ODA_DRAWENTIRE) = ODA_DRAWENTIRE) then begin

    Font := SelectObject(Msg.DrawItemStruct.hDC, ComboBox1.Canvas.Font.Handle);
    SelectObject(Msg.DrawItemStruct.hDC, GetStockObject(DC_BRUSH));

    if (Msg.DrawItemStruct.itemState and ODS_SELECTED) = ODS_SELECTED then begin
      SetDCBrushColor(Msg.DrawItemStruct.hDC, ColorToRGB(clHighlight));
      SetBkColor(Msg.DrawItemStruct.hDC, ColorToRGB(clHighlight));
      SetTextColor(Msg.DrawItemStruct.hDC, ColorToRGB(clHighlightText));
    end else begin
      SetDCBrushColor(Msg.DrawItemStruct.hDC, ColorToRGB(clWindow));
      SetBkColor(Msg.DrawItemStruct.hDC, ColorToRGB(clWindow));
      SetTextColor(Msg.DrawItemStruct.hDC, ColorToRGB(clWindowText));
    end;

    FillRect(Msg.DrawItemStruct.hDC, Msg.DrawItemStruct.rcItem, 0);
    TextOut(Msg.DrawItemStruct.hDC, 4, 4, '_no_selected_item_', 18);

    SelectObject(Msg.DrawItemStruct.hDC, Font);
  end;
end;

答案 3 :(得分:0)

我认为你想要正常的事情,在尚未做出任何选择的情况下在ComboBox中显示内容。一个空白矩形的瞬间。想象一个充满空白组合框的表格......;)

我看过大多数程序员所做的是将第一个项目作为要在ComboBox中显示的标题。

因此,在FormCreate中(在您填充ComboBox之后),将其ItemIndex设置为0,这将显示标题。

在其OnChange事件中,如果选择了项目0,则可以选择不执行任何操作(“真实”项目然后具有索引的基础1),或者如果<“则获取ItemIndex-1并跳过操作。 0

必须是第一次使用Comboboxes的每个人的超级常见投诉。我无法理解编码员是如何认识它的。

Borland等人所要做的就是用ItemIndex = 0来初始化一个新的ComboBox,并且混乱就会消失。你必须设置索引0肯定不明显 - 因为你点击时看到空行,逻辑结论是有索引0.可能他们想给设计师添加标签的选项改为在组合框外面。