一般地,我们用ComboBoxEdit来实现下拉单选,但它的item只能一个字符串,而不是一个自定义的对象。因此,我们常用CheckedComboBoxEdit来代替ComboBoxEdit,但CheckedComboBoxEdit默认是可以多选的,所以,我们要写一个单选处理事件。效果如下:
自定义对象:
1 2 3 4 5 6 7 8 9 10 11 | private static DataTable CreateTable( int rowCount) { DataTable datatable = new DataTable(); datatable.Columns.Add( "Name" , typeof ( string )); datatable.Columns.Add( "ID" , typeof ( int )); datatable.Columns.Add( "Number" , typeof ( int )); datatable.Columns.Add( "Date" , typeof (DateTime)); for ( int i = 0; i < rowCount; i++) datatable.Rows.Add( new object [] { $ "选项 {i}" , i, 3 - i, DateTime.Now.AddDays(i) }); return datatable; } |
绑定数据:
1 2 3 4 | checkedComboBoxEdit1.Properties.DataSource = CreateTable(10); checkedComboBoxEdit1.Properties.DisplayMember = "Name" ; checkedComboBoxEdit1.Properties.ValueMember = "ID" ; checkedComboBoxEdit1.Properties.SelectAllItemVisible = false ; |
弹出窗口事件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | private void checkedComboBoxEdit1_Popup( object sender, EventArgs e) { CheckedListBoxControl checkedListBoxControl = (sender as IPopupControl)?.PopupWindow.Controls.OfType<PopupContainerControl>().First().Controls.OfType<CheckedListBoxControl>().First(); if (checkedListBoxControl != null ) { checkedListBoxControl.ItemCheck -= checkedListBoxControl_ItemCheck; checkedListBoxControl.ItemCheck += checkedListBoxControl_ItemCheck; } } private void checkedListBoxControl_ItemCheck( object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e) { if (e.State == CheckState.Checked) { CheckedListBoxControl list = sender as CheckedListBoxControl; List<CheckedListBoxItem> items = new List<CheckedListBoxItem>(); foreach ( int index in list.CheckedIndices) { if (index == e.Index) continue ; items.Add(list.Items[index]); } foreach (CheckedListBoxItem item in items) item.CheckState = CheckState.Unchecked; } } |