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 将枚举绑定到单选按钮
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01