Best way to databind a group of radiobuttons in WinForms

前端 未结 9 565
无人共我
无人共我 2020-12-03 00:58

I\'m currently working on databinding some of my existing Windows Forms, and I\'ve ran into an issue figuring out the proper way of databinding a group of radiobutton contro

9条回答
  •  生来不讨喜
    2020-12-03 01:49

    This is my approach for binding a list of radio buttons to an enum.

    Using the Enum as a string in the button's Tag property, I use the Binding.Format and Binding.Parse event to decide which button should be checked.

    public enum OptionEnum
    {
       Option1 = 0,
       Option2
    }
    
    OptionEnum _rbEnum = OptionEnum.Option1;
    OptionEnum PropertyRBEnum
    {
        get { return _rbEnum; }
        set
        {
            _rbEnum = value;
            RaisePropertyChanged("PropertyRBEnum");
        }
    }
    
    public static void FormatSelectedEnum(object sender, ConvertEventArgs args) where T : struct
    {
        Binding binding = (sender as Binding);
        if (binding == null) return;
    
        Control button = binding.Control;
    
        if (button == null || args.DesiredType != typeof(Boolean)) return;
    
        T value = (T)args.Value;
        T controlValue;
    
        if (Enum.TryParse(button.Tag.ToString(), out controlValue))
        {
            args.Value = value.Equals(controlValue);
        }
        else
        {
            Exception ex = new Exception("String not found in Enum");
            ex.Data.Add("Tag", button.Tag);
    
            throw ex;
        }
    }
    
    public static void ParseSelectedEnum(object sender, ConvertEventArgs args) where T : struct
    {
        Binding binding = (sender as Binding);
        if (binding == null) return;
    
        Control button = binding.Control;
        bool value = (bool)args.Value;
    
        if (button == null || value != true) return;
    
        T controlValue;
    
        if (Enum.TryParse(button.Tag.ToString(), out controlValue))
        {
            args.Value = controlValue;
        }
        else
        {
            Exception ex = new Exception("String not found in Enum");
            ex.Data.Add("Tag", button.Tag);
    
            throw ex;
        }
    }
    

    Then setup your data binding like this:

    radioButton1.Tag = "Option1";
    radioButton2.Tag = "Option2";
    
    foreach (RadioButtonUx rb in new RadioButtonUx[] { radioButton1, radioButton2 })
    {
        Binding b = new Binding("Checked", this, "PropertyRBEnum");
        b.Format += FormatSelectedRadioButton;
        b.Parse += ParseSelectedRadioButton;
    
        rb.DataBindings.Add(b);
    }
    

提交回复
热议问题