对于枚举的每个值,您需要创建一个
RadioButton
并将其
Checked
值绑定到数据源的
Mode
属性。然后,您需要使用
Binding
的
Format
和
Parse
事件将
Mode
值转换为适合
Checked
属性的值,反之亦然。
示例 - 使用FlowLayoutPanel的RadioButton列表
例如,在表单上放置一个
FlowLayoutPanel
控件,然后在
Form
的
Load
事件中编写以下代码。该代码将动态向流式布局面板添加
RadioButton
控件并执行数据绑定。
var enumValues = Enum.GetValues(typeof(SomeModeType)).Cast<object>()
.Select(x => new { Value = x, Name = x.ToString() }).ToList();
enumValues.ForEach(x =>
{
var radio = new RadioButton() { Text = x.Name, Tag = x.Value };
var binding = radio.DataBindings.Add("Checked", dataSource,
"Mode", true, DataSourceUpdateMode.OnPropertyChanged);
binding.Format += (obj, ea) =>
{ ea.Value = ((Binding)obj).Control.Tag.Equals(ea.Value); };
binding.Parse += (obj, ea) =>
{ if ((bool)ea.Value == true) ea.Value = ((Binding)obj).Control.Tag; };
flowLayoutPanel1.Controls.Add(radio);
});
在上面的例子中,
dataSource
可以是一个
MyCustomObject
或者一个
BindingList<MyCustomObject>
或者一个包含
List<MyCustomObject>
的
BindingSource
。
另一种选择 - 使用自定义绘制的 RadioButton List
作为另一种选择,您可以使用自定义绘制的
ListBox
并为项目渲染
RadioButton
。这样,您可以将
ListBox
的
SelectedValue
绑定到对象的
Mode
属性。在以下代码中,
dataSource
可以像上面的例子一样。在窗体上放置一个
ListBox
并在窗体的
Load
事件中编写以下代码:
var enumValues = Enum.GetValues(typeof(SomeModeType)).Cast<object>()
.Select(x => new ).ToList();
this.listBox1.DataSource = enumValues;
this.listBox1.ValueMember = "Value";
this.listBox1.DisplayMember = "Name";
this.listBox1.DataBindings.Add("SelectedValue", dataSource,
"Mode", true, DataSourceUpdateMode.OnPropertyChanged);
this.listBox1.DrawMode = DrawMode.OwnerDrawFixed;
this.listBox1.ItemHeight = RadioButtonRenderer.GetGlyphSize(
Graphics.FromHwnd(IntPtr.Zero),
RadioButtonState.CheckedNormal).Height + 4;
this.listBox1.DrawItem += (obj, ea) =>
;
屏幕截图
您可以在以下图片中看到两种解决方案:
![enter image description here](https://istack.dev59.com/lGhyG.gif)
var list = new List<MyCustomObject>() {
new MyCustomObject(){ Mode= SomeModeType.firstMode},
new MyCustomObject(){ Mode= SomeModeType.secondMode},
new MyCustomObject(){ Mode= SomeModeType.thirdMode},
};
this.myCustomObjectBindingSource.DataSource = list;
var dataSource = myCustomObjectBindingSource;
注意
在回答这个问题后,我创建了并分享了一个RadioButtonList
控件在这篇文章中:WinForms RadioButtonList doesn't exist。
它支持数据绑定,你可以像使用ListBox
一样使用该控件。要做到这一点,只需将其绑定到模型的属性上,然后设置控件的数据源即可:
radioButtonList1.DataSource = Enum.GetValues(typeof(YourEnumType));
List<SomeModeType>
为属性,并用枚举的每个成员填充它。 - Anup SharmaRadioButtonList
控件 链接。 - Reza AghaeiListBox
一样使用此控件。为此,只需将其绑定到模型的属性,然后以这种简单的方式设置控件的数据源即可:radioButtonList1.DataSource = Enum.GetValues(typeof(YourEnumType));
- Reza Aghaei