CheckedComboBoxEdit实现单选

一般地,我们用ComboBoxEdit来实现下拉单选,但它的item只能一个字符串,而不是一个自定义的对象。因此,我们常用CheckedComboBoxEdit来代替ComboBoxEdit,但CheckedComboBoxEdit默认是可以多选的,所以,我们要写一个单选处理事件。效果如下:

自定义对象:

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;
}

绑定数据:

checkedComboBoxEdit1.Properties.DataSource = CreateTable(10);
checkedComboBoxEdit1.Properties.DisplayMember = "Name";
checkedComboBoxEdit1.Properties.ValueMember = "ID";
checkedComboBoxEdit1.Properties.SelectAllItemVisible = false;

弹出窗口事件:

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;
    }
}
posted @ 2021-04-08 14:36  我也是个傻瓜  阅读(1084)  评论(0编辑  收藏  举报