【发布时间】:2021-06-12 11:40:07
【问题描述】:
最近几天我一直在寻找解决这个问题的方法,但还没有找到合适的解决方案。我制作了一个带有选中列表框的 WinForm,它必须表现为单选按钮组。我知道这不是可取的,但我自己没有选择这个。我正在尝试扩展我对 WinForm 的了解,所以我抓住了一个程序并尝试模仿这种行为,所以请留在我身边。
我想要在我的选中列表框中的单选按钮属性:
- 您只能检查一项。 (操作简单,见下方代码)
- 始终选中一个项目。 (这是我问题的根源)
- 当您单击复选框/项目符号时,它会一键检查,单击文本不会更改任何内容。 (我也想出了一个)
我需要的 Checkedlistbox 属性:
- 复选框后面的可选文本。 (用于重命名和删除列表中的项目)
我大部分时间都在工作,除非选择了一个项目而未选中另一个项目。那时列表中的每个项目都可以取消选中。
这是 ItemCheck 事件的代码。
private string _checkedName = "";
bool _autorizeCheck {get; set;}
private void OnItemCheck(object sender, ItemCheckEventArgs e)
{
var list = sender as CheckedListBox;
#region//Click checkbox
if (!_authorizeCheck)
{
e.NewValue = e.CurrentValue;
}
#endregion
#region//Radiobutton config
if (e.CurrentValue == CheckState.Unchecked)
{
for (int i = 0; i < list.Items.Count; i++)
{
if (i != e.Index)
{
_checkedName = list.Items[e.Index].ToString();
list.SetItemChecked(i, false);
}
}
}
else if(e.CurrentValue == CheckState.Checked && _checkedName == list.Items[e.Index].ToString())
{
if (list.CheckedItems.Count == 1)
{
e.NewValue = e.CurrentValue;
}
}
#endregion
}
这是点击复选框的代码:
private void OnMouseDown_checkedListBox(object sender, MouseEventArgs e)
{
#region//Check if checkbox is clicked
var checkedListBox = sender as CheckedListBox;
var location = checkedListBox.PointToClient(Cursor.Position);
for (int i = 0; i < checkedListBox.Items.Count; i++)
{
var rec = checkedListBox.GetItemRectangle(i);
rec.Width = 16;
if (rec.Contains(location))
{
_authorizeCheck = true;
bool newValue = !checkedListBox.GetItemChecked(i);
checkedListBox.SetItemChecked(i, newValue);
_authorizeCheck = false;
return;
}
}
#endregion
}
【问题讨论】:
-
您正在寻找RadioButtonList。
-
谢谢 Reza,我用 CheckedListBox 修复了它,因为我想要 CheckedListBox 的美感