Combobox控件在开发中作为下拉选项的不二之选,用的非常频繁,前几日开发过程中刚好有个需求有用到这个控件,而且客户要求增加下拉选择功能,这个简单,设置控件的自动完成属性后就解决了boBox1.AutoCompleteSource=AutoCompleteSource.ListItems;//设置自动完成的源
boBox1.AutoCompleteMode=AutoCompleteMode.SuggestAppend;//设置自动完成的的形式
发现场让客户使用,客户表示功能实现和他需求不一致,后来解释是想通过下拉选项的拼音码进行检索,查遍的很多资料,也走了很多弯路,最后终于实现,将正确的实现方法记录在此
首先根据Combobox控件拼音码检索搜索到了这篇文章(/eshizhan/archive//08/13/2637207.html),集成到项目中进行测试时发现,输入检索的内容后,敲击回车键,输入的内容没有全部显示到文本框中,输入三个字母时,只显示一个或者两个,再次检索时候恢复正常
如果检索时,把鼠标指针从控件上移动到别的控件上,输入检索内容敲击回车键后,会出现丢失鼠标指针的情况,这时只有把鼠标往下移动到任务栏指针才会出现
以上问题测试均使用搜狗输入法中文状态
网上并没有找到针对这两个问题的解决方案,继续搜索拼音码检索,查找不同的方案,经过对多个方案的反复测试,终于发现了一个可用的方案,重写了ComboBox控件,以下为示例代码publicclassComboBoxEx:System.boBox
{
publicComboBoxEx()
{
this.FormattingEnabled=true;
}
List_ChineseCharacterList;
privatestring[]_TextList;
publicstring[]TextList
{
get{return_TextList;}
set
{
_TextList=value;
_ChineseCharacterList=GetChineseCharacterList(value);
}
}
///
///把中文字符集合转为中文字符对象集合
///
privateListGetChineseCharacterList(string[]chnTextList)
{
Listlst=newList();
foreach(stringsinchnTextList)
{
ChineseCharactercc=newChineseCharacter(s);
lst.Add(cc);
}
returnlst;
}
protectedoverridevoidOnTextUpdate(EventArgse)
{
if(_ChineseCharacterList!=null&&_ChineseCharacterList.Count>0)
{
//varinput=this.Text.Trim().ToUpper();
stringinput=this.Text.Trim().ToUpper();
this.Items.Clear();
if(string.IsNullOrEmpty(input))
{
this.Items.AddRange(_ChineseCharacterList.ToArray());
}
else
{
varnewList=_ChineseCharacterList.FindAll(c=>c.FirstPinYin.Contains(input)||c.ChineseText.Contains(input));
if(newList.Count==0)
{
newList.Add(newChineseCharacter("未找到"));
}
this.Items.AddRange(newList.ToArray());
}
this.DisplayMember="ChineseText";
this.ValueMember="FirstPinYin";
this.Select(this.Text.Length,0);
this.DroppedDown=true;
//保持鼠标指针形状
Cursor=Cursors.Default;
}
base.OnTextUpdate(e);
}
protectedoverridevoidOnEnter(EventArgse)
{
this.Items.AddRange(_ChineseCharacterList.ToArray());
this.DisplayMember="ChineseText";
this.ValueMember="FirstPinYin";
base.OnEnter(e);
}
protectedoverridevoidOnLeave(EventArgse)
{
this.Items.Clear();
base.OnLeave(e);
}
}
///
///中文字符
///
publicclassChineseCharacter
{
publicChineseCharacter(stringchnText)
{
ChineseText=chnText;
FirstPinYin=JHNISCommonLib.JHNISCommonManage.GetInstance().JianPin(chnText);
}
publicstringChineseText{get;set;}
publicstringFirstPinYin{get;set;}
}
第二种方案,使用搜索输入法输入汉字,敲击回车键后,输入的内容没有全部显示到Combobox控件上,如下图所示(输入“浏览器”,只显示了“览器”):
经测试当把下拉列表显示出来再进行检索时,内容显示正常,可通过以下代码进行设置protectedoverridevoidOnGotFocus(EventArgse)
{
this.DroppedDown=true;
base.OnGotFocus(e);
}
protectedoverridevoidOnLostFocus(EventArgse)
{
this.DroppedDown=false;
base.OnLostFocus(e);
}