1、为什么要使用控件的重写?
从需求角度出发,例如一个ComcoBox实现简单的下拉选择,按照原始的控件,其能实现的只是最简单的单个数据的选择。如果现在有一个需求是需要该控件实现多个数据同时选择和重置已选择的数据,此时需要对该控件实现重写。
2、如果实现?
- 界面控件放置一个ComcoBox
- 规范化命名,cb_XXX
- 重新添加一个
- 项目
3、代码展示
步骤 1: 创建自定义 ComboBox 控件
创建一个新的自定义 ComboBox 控件:
在 Visual Studio 中,右击项目并选择“添加” > “新项”。
选择“类”并命名为 MultiSelectComboBox.cs。
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
public class MultiSelectComboBox : ComboBox
{
private List _selectedItems = new List();
public MultiSelectComboBox()
{
// Set DropDownStyle to DropDownList to prevent direct text input
this.DropDownStyle = ComboBoxStyle.DropDownList;
}
protected override void OnDropDown(EventArgs e)
{
base.OnDropDown(e);
PopulateDropDown();
}
private void PopulateDropDown()
{
// Create a new form to hold the check list
Form checkListForm = new Form();
CheckBox[] checkBoxes = new CheckBox[this.Items.Count];
int y = 10;
for (int i = 0; i < this.Items.Count; i++)
{
CheckBox cb = new CheckBox
{
Text = this.Items[i].ToString(),
Location = new Point(10, y),
Checked = _selectedItems.Contains(this.Items[i].ToString())
};
cb.CheckedChanged += (s, e) =>
{
if (cb.Checked)
{
if (!_selectedItems.Contains(cb.Text))
{
_selectedItems.Add(cb.Text);
}
}
else
{
_selectedItems.Remove(cb.Text);
}
UpdateText();
};
checkBoxes[i] = cb;
y += 25;
}
Button btnSelectAll = new Button
{
Text = "全选",
Location = new Point(10, y)
};
btnSelectAll.Click += (s, e) =>
{
foreach (var cb in checkBoxes)
{
cb.Checked = true;
}
_selectedItems.Clear();
_selectedItems.AddRange(this.Items.OfType<string>());
UpdateText();
};
checkListForm.Controls.Add(btnSelectAll);
Button btnCancel = new Button
{
Text = "取消",
Location = new Point(btnSelectAll.Right + 10, y)
};
btnCancel.Click += (s, e) => checkListForm.Close();
checkListForm.Controls.Add(btnCancel);
checkListForm.Controls.AddRange(checkBoxes);
checkListForm.StartPosition = FormStartPosition.CenterParent;
checkListForm.Size = new Size(200, y + 60);
checkListForm.ShowDialog(this);
}
private void UpdateText()
{
this.Text = string.Join(", ", _selectedItems);
}
}
步骤 2: 使用自定义 ComboBox 控件
将自定义控件添加到 Windows Forms 窗体:
打开你的 Windows Forms 设计视图。
从工具箱中选择“选择工具箱项”,然后在“浏览”选项卡中添加你的自定义控件类 (MultiSelectComboBox),或直接将 .cs 文件拖放到设计器中。
使用自定义控件:
将 MultiSelectComboBox 拖放到你的窗体上。
设置 Items 属性来添加下拉项。
运行你的应用程序,你会看到自定义的多选下拉框功能。
在这里插入代码片