Winforms Bind Enum to Radio Buttons(Winforms 将枚举绑定到单选按钮)
问题描述
如果我有三个单选按钮,将它们绑定到具有相同选择的枚举的最佳方法是什么?例如
If I have three radio buttons, what is the best way to bind them to an enum which has the same choices? e.g.
[] Choice 1
[] Choice 2
[] Choice 3
public enum MyChoices
{
Choice1,
Choice2,
Choice3
}
推荐答案
我知道这是一个老问题,但它是第一个出现在我的搜索结果中的问题.我想出了一种将单选按钮绑定到枚举,甚至是字符串或数字等的通用方法.
I know this is an old question, but it was the first to show up in my search results. I figured out a generic way to bind radio buttons to an enum, or even a string or number, etc.
private void AddRadioCheckedBinding<T>(RadioButton radio, object dataSource, string dataMember, T trueValue)
{
var binding = new Binding(nameof(RadioButton.Checked), dataSource, dataMember, true, DataSourceUpdateMode.OnPropertyChanged);
binding.Parse += (s, a) => { if ((bool)a.Value) a.Value = trueValue; };
binding.Format += (s, a) => a.Value = ((T)a.Value).Equals(trueValue);
radio.DataBindings.Add(binding);
}
然后在表单的构造函数或表单加载事件上,在每个 RadioButton
控件上调用它.dataSource
是包含您的枚举属性的对象.我确保 dataSource
实现了 INotifyPropertyChanged
接口正在触发枚举属性设置器中的 OnPropertyChanged
事件.
And then either on your form's constructor or on the form load event, call it on each of your RadioButton
controls.
The dataSource
is the object containing your enum property. I made sure that dataSource
implemented the INotifyPropertyChanged
interface is firing the OnPropertyChanged
event in the enum properties setter.
AddRadioCheckedBinding(Choice1RadioButton, dataSource, "MyChoice", MyChoices.Choice1);
AddRadioCheckedBinding(Choice2RadioButton, dataSource, "MyChoice", MyChoices.Choice2);
这篇关于Winforms 将枚举绑定到单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Winforms 将枚举绑定到单选按钮
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01