对于枚举的每个值,您需要创建一个RadioButton
并将其Checked
值绑定到数据源的Mode
属性。那么您需要使用Format
和Parse
事件Binding
将Mode
值转换为Checked
属性的合适值,反之亦然。
实施例 - 单选按钮列表使用FlowLayoutPanel的
例如把一个FlowLayoutPanel
控制窗体上,然后在Load
事件Form
写的以下代码。该代码将动态添加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>
或含有在其DataSource
一个List<MyCustomObject>
一个BindingSource
。使用重绘列表框
作为另一个选项,您可以使用一个所有者绘制ListBox
和项目呈现RadioButton
单选按钮列表 -
另一种选择。这样,您可以将SelectedValue
的ListBox
绑定到您的对象的Mode
属性。以下代码中的dataSourcs
可以像上面的例子。穿上形式ListBox
写下面的代码Load
活动形式:
var enumValues = Enum.GetValues(typeof(SomeModeType)).Cast<object>()
.Select(x => new { Value = x, Name = x.ToString() }).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) =>
{
var lb = (ListBox)obj;
ea.DrawBackground();
var text = lb.GetItemText(lb.Items[ea.Index]);
var r = ea.Bounds;
r.Offset(ea.Bounds.Height, 0);
RadioButtonRenderer.DrawRadioButton(ea.Graphics,
new Point(ea.Bounds.Location.X, ea.Bounds.Location.Y + 2), r, text,
lb.Font, TextFormatFlags.Left, false,
(ea.State & DrawItemState.Selected) == DrawItemState.Selected ?
RadioButtonState.CheckedNormal : RadioButtonState.UncheckedNormal);
};
截图
你可以看到下面的图片这两个解决方案:
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'作为属性,并填写每个枚举的成员 –
@AnupSharma,但如何帮助? 我的意思是,为什么不直接绑定单选按钮就好像 - 如果选择1st,则字段值将变为firstMode,如果是2nd,则将字段值重写为secondMode – DanilGholtsman
我共享一个RadioButtonList控件[here] (http://stackoverflow.com/a/41355419/3110834)。 –