Winforms 将枚举绑定到单选按钮
如果我有三个单选按钮,将它们绑定到具有相同选择的枚举的最佳方法是什么?例如
[] Choice 1
[] Choice 2
[] Choice 3
public enum MyChoices
{
Choice1,
Choice2,
Choice3
}
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我知道这是一个老问题,但它是第一个出现在我的搜索结果中的问题。我找到了一种将单选按钮绑定到枚举,甚至是字符串或数字等的通用方法。
然后在表单的构造函数或表单加载事件上,在每个
RadioButton
控制。dataSource
是包含枚举属性的对象。我确保dataSource
实现的INotifyPropertyChanged
接口正在触发枚举属性设置器中的OnPropertyChanged
事件。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.
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 thatdataSource
implemented theINotifyPropertyChanged
interface is firing theOnPropertyChanged
event in the enum properties setter.您可以创建三个布尔属性:
然后绑定到 MyChoice_Choice1 和其他属性吗?
Could you create three boolean properties:
then bind to MyChoice_Choice1 and the others?
我只是想添加我目前正在做的方式。本身没有“约束力”,但希望它能起到同样的作用。
欢迎评论。
I just thought I'd add the way that I'm currently doing it. There's no 'binding' as such but hopefully it does the same job.
Comments welcome.
提问者没有提及他的约束力是什么。我想他绑定到 XXX.Properties.Settings 类。如果没有,此解决方案需要绑定类来实现 INotifyPropertyChanged 接口。
并有一个像这样的索引器:
我尝试了 WeskerTyrant 提供的可接受的解决方案,但失败了。
我必须点击两次才能起作用。
于是我开始自己解决问题。我注意到我绑定的类实现了 INotifyPropertyChanged 接口。其中有一个名为 PropertyChanged 的 PropertyChangedEventHandler。
(顺便说一句,我正在使用.net 472)
所以我自己写了一个辅助类。
使用时。您只需在 form_load 事件中添加以下代码即可。
我在 github 上分享了这个:
https://github.com/EricWebsmith/Ezfx.Dui
我我猜人们会投票否决我,因为这不能回答有关枚举的问题。我的解决方案是在使用时强制转换设置。就我而言,我使用 python 脚本中的设置,因此不需要强制转换。
The question poster did not mention what he is binding to. I suppose he is binding to the XXX.Properties.Settings class. If not, this solution need the binding class to implement INotifyPropertyChanged interface.
and has an indexer like this:
I tried the accepted solution, provided by WeskerTyrant, but failed.
I had to click twice before it works.
So I started to solve the problem by myself. I noticed that the class I am binding to implements the INotifyPropertyChanged interface. whiche has a PropertyChangedEventHandler called PropertyChanged.
(I am using .net 472 by the way)
So I wrote a helper class myself.
When using it. You simply add the following code in the form_load event.
I shared this in github:
https://github.com/EricWebsmith/Ezfx.Dui
I guess people will vote me down because this does not answer the question about enum. My solution is to cast the settings when use. In my case, I use the settings in a python script, so there is no need to cast.