Windows窗体 – 如何在C#中的combobox项目中添加标题无法选择?

我需要创建一个自定义combobox控件,允许标题作为分隔符,不能使用鼠标移动或按键选择。

这是一个例子:

Header1 item1 item2 item3 Header2 item4 item5 

我尝试了很多解决方案,没有成功。 提前致谢!

再次,WPF可以轻松提供解决方案,需要在winforms中进行大量可怕的攻击。

将我的代码复制并粘贴到Visual Studio中的文件 – >新建项目 – > WPF应用程序中。

您很快就会注意到我的解决方案不仅为Header Items提供了不同的视觉外观,而且还可以防止不必要的选择,无论是通过鼠标还是键盘,并且它不需要子类化常规的ComboBox类,这会导致较小的可维护性。

组合框

XAML:

          

代码背后:

 using System.Collections.Generic; using System.Windows; namespace WpfApplication5 { public partial class Window2 : Window { public Window2() { InitializeComponent(); var list = new List { new ComboBoxItem {DisplayText = "Header1", IsHeader = true}, new ComboBoxItem {DisplayText = "Item1", IsHeader = false}, new ComboBoxItem {DisplayText = "Item2", IsHeader = false}, new ComboBoxItem {DisplayText = "Item3", IsHeader = false}, new ComboBoxItem {DisplayText = "Header2", IsHeader = true}, new ComboBoxItem {DisplayText = "Item4", IsHeader = false}, new ComboBoxItem {DisplayText = "Item5", IsHeader = false}, new ComboBoxItem {DisplayText = "Item6", IsHeader = false}, }; DataContext = list; } } public class ComboBoxItem { public string DisplayText { get; set; } public bool IsHeader { get; set; } } } 

试试这个自定义combobox。 它会忽略标题,但标题的绘制方式与任何其他项目完全相同,当您选择子项时,它将包含这些额外的空格。 但希望这会引导您朝着正确的方向前进。

 public class CustomComboBox : ComboBox { int currentlySelectedIndex = -1; protected override void OnSelectionChangeCommitted(EventArgs e) { if (this.SelectedIndex != -1) { // Check if we shouldn ignore it: object currentlySelectedItem = this.Items[this.SelectedIndex]; if (ShouldIgnore(currentlySelectedItem)) { Console.WriteLine("Ignoring it! Resetting the index."); this.SelectedIndex = currentlySelectedIndex; } } base.OnSelectionChangeCommitted(e); } protected virtual bool ShouldIgnore(object selectedItem) { // This is a category if it starts with a space. return !selectedItem.ToString().StartsWith(" "); } protected override void OnDropDown(EventArgs e) { // Save the current index when the drop down shows: currentlySelectedIndex = this.SelectedIndex; base.OnDropDown(e); } }