可编辑历史记录组合框
演示如何轻松模拟一个可编辑的组合框,它可以保留之前的条目(就像 Internet Explorer)。
引言
Compact Framework 并没有提供可编辑组合框的选项,但有一个简单的方法可以解决这个限制。以下文章将解释如何创建一个可编辑的组合框,它可以记住最多 10 个之前的条目(就像 Internet Explorer 的地址栏一样)。
使用代码
要使组合框可编辑,你只需将文本框覆盖在组合框上。为了使文本框和组合框无缝地结合在一起,你可以像这样在每个组合框中添加代码
int dropDownButtonWidth = 14;
txtTest1.Bounds = cboTest1.Bounds;
txtTest1.Width -= dropDownButtonWidth;
现在,为了完成可编辑组合框的行为,你只需要确保文本框使用组合框中当前选定的项目进行更新。请参考下面的代码
private void cboTest1_SelectedIndexChanged(object sender, System.EventArgs e)
{
txtTest1.Text = cboTest1.Text;
}
这些就是你获得可编辑组合框行为所需的一切。如果你想创建一个历史记录组合框,你需要一个 XML 文件来持久化组合框条目。加载过去条目的代码非常简单。
// Load the combobox entries from the XML file.
xdoc.Load(@"\Path to comboboxes.xml");
XmlElement root = xdoc.DocumentElement;
XmlNodeList nodeList = root.ChildNodes;
ComboBox cboHistory;
for(int j=0; j<nodeList.Item(i).ChildNodes.Count; ++j)
{
cboHistory.Items.Add(nodeList.Item(i).ChildNodes.Item(j).InnerText);
}
保存新条目的代码稍微复杂一些,但也不难。int maxEntriesToStore = 10;
XmlTextWriter tw = new XmlTextWriter(@"\Path to comboboxes.xml",
System.Text.Encoding.UTF8);
tw.WriteStartDocument();
tw.WriteStartElement("comboboxes");
tw.WriteStartElement("combobox");
tw.WriteStartAttribute("name", string.Empty);
tw.WriteString("cboTest1");
tw.WriteEndAttribute();
// Write the item from the text box first.
if(txtTest1.Text.Length != 0)
{
tw.WriteStartElement("entry");
tw.WriteString(txtTest1.Text);
tw.WriteEndElement();
maxEntriesToStore -= 1;
}
// Write the rest of the entries (up to 10).
for(int i=0; i < cboTest1.Items.Count && i < maxEntriesToStore; ++i)
{
if(txtTest1.Text != cboTest1.Items[i].ToString())
{
tw.WriteStartElement("entry");
tw.WriteString(cboTest1.Items[i].ToString());
tw.WriteEndElement();
}
}
tw.WriteEndElement();
tw.WriteEndElement();
tw.Flush();
tw.Close();
演示项目包含处理 3 个组合框的代码,并且安排方式与上面的示例代码略有不同。祝你玩得开心! 