Winforms将Enum绑定到单选按钮

Dam*_*ien 7 c# data-binding enums radio-button winforms

如果我有三个单选按钮,将它们绑定到具有相同选择的枚举的最佳方法是什么?例如

[] Choice 1
[] Choice 2
[] Choice 3

public enum MyChoices
{
    Choice1,
    Choice2,
    Choice3
}
Run Code Online (Sandbox Code Playgroud)

Wes*_*ant 8

我知道这是一个老问题,但它是第一个出现在我的搜索结果中的问题。我想出了一种将单选按钮绑定到枚举,甚至是字符串或数字等的通用方法。

    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);
    }
Run Code Online (Sandbox Code Playgroud)

然后在窗体的构造函数或窗体加载事件上,在每个RadioButton控件上调用它。该dataSource是包含您枚举属性的对象。我确保dataSource实现的INotifyPropertyChanged接口OnPropertyChanged在枚举属性设置器中触发事件。

AddRadioCheckedBinding(Choice1RadioButton, dataSource, "MyChoice", MyChoices.Choice1);
AddRadioCheckedBinding(Choice2RadioButton, dataSource, "MyChoice", MyChoices.Choice2);
Run Code Online (Sandbox Code Playgroud)

  • 伙计,这可是救命啊!几乎试图创建另一个个人资料只是为了两次投票!当然,我将其转换为扩展方法:`public static void AddRadioCheckedBinding&lt;T&gt;(this RadioButton radio, object dataSource, string dataMember, T trueValue)` (2认同)