Winforms 将枚举绑定到单选按钮

Winforms Bind Enum to Radio Buttons(Winforms 将枚举绑定到单选按钮)

本文介绍了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 将枚举绑定到单选按钮

基础教程推荐