【发布时间】:2015-09-22 07:35:19
【问题描述】:
这里是 VCL 组件新手,如果这是一个愚蠢的问题,请原谅我......
我正在尝试制作一个包含默认项目的 TComboBox 组件,然后将其拖放到表单上,即一个 TMonthComboBox,当拖放到表单上时,其项目列表中将包含月份列表。
我发现在构造过程中尝试访问 Items 属性会导致“Control '' has no parent window”错误,如果我尝试将此类组合框拖放到表单上。 p>
这里是(部分)构造函数:
__fastcall TMonthCombo::TMonthCombo(TComponent *Owner):TComboBox(Owner)
{
this->Style = csDropDownList; // this is okay
this->Items->Add("January"); // This is causing problem
}
我认为问题是由于 Items 属性在构造的这个时候还不可用。
是否有办法确保组件已准备好在组件源代码本身内将值接受到其 Items 属性中(即在设计时不在属性编辑器中添加列表项)?
在有人告诉我“只需在运行时将项目添加到您的应用程序代码中”之前,我必须解释一下,这个 ComboBox 将在很多地方非常频繁地使用,而月份选择只是我用来解释的一个简单示例问题是,我想放在 ComboBox 中的实际值要多样化得多,而且大多数时候是动态的。它还必须以多种方式响应用户的选择。
我已经尝试过运行时的方式,但它变得非常乏味。这就是我将它制作成一个组件的原因,这样它就可以自行处理,而无需我重复输入多个版本的代码来填充 ComboBox。
感谢您的帮助。
编辑:在尝试了 manlio 的解决方案后,ComboBox 在运行时看起来很奇怪:
ComboBox 在运行时具有双图像。我做错了什么?
__fastcall TYearCombo::TYearCombo(TComponent* Owner) : TComboBox(Owner), init_items(true)
{
}
//---------------------------------------------------------------------------
void __fastcall TYearCombo::CreateWnd()
{
unsigned short yr, mn, dy;
this->Width = 90;
this->Style = csDropDownList;
this->DropDownCount = 11;
TDate d = Today();
d.DecodeDate(&yr, &mn, &dy);
year = yr;
if (init_items)
{
init_items = false;
TComboBox::CreateWnd();
Items->BeginUpdate();
for(int i=year-5; i<=year+5; i++)
{
Items->Add(IntToStr(i));
}
this->ItemIndex = 5;
Items->EndUpdate();
}
}
//---------------------------------------------------------------------------
【问题讨论】:
-
如果我删除 this->Width = 90;线,那么它工作得很好。
标签: c++ c++builder vcl tcombobox