Dam*_*ien 7 c# data-binding enums radio-button winforms
如果我有三个单选按钮,将它们绑定到具有相同选择的枚举的最佳方法是什么?例如
[] Choice 1
[] Choice 2
[] Choice 3
public enum MyChoices
{
    Choice1,
    Choice2,
    Choice3
}
我知道这是一个老问题,但它是第一个出现在我的搜索结果中的问题。我想出了一种将单选按钮绑定到枚举,甚至是字符串或数字等的通用方法。
    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在枚举属性设置器中触发事件。
AddRadioCheckedBinding(Choice1RadioButton, dataSource, "MyChoice", MyChoices.Choice1);
AddRadioCheckedBinding(Choice2RadioButton, dataSource, "MyChoice", MyChoices.Choice2);
| 归档时间: | 
 | 
| 查看次数: | 7186 次 | 
| 最近记录: |