Winforms Bind Enum to Radio Buttons
Asked Answered
S

4

12

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
}
Sanguine answered 19/3, 2010 at 11:33 Comment(0)
P
14

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);
    }

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);
Pussyfoot answered 15/12, 2017 at 22:53 Comment(1)
Man, this is life-saving! Almost trying to create another profile just to UpVote twice! Of course I transformed it in an Extension Method: public static void AddRadioCheckedBinding<T>(this RadioButton radio, object dataSource, string dataMember, T trueValue)Gean
H
2

Could you create three boolean properties:

private MyChoices myChoice;

public bool MyChoice_Choice1
{
    get { return myChoice == MyChoices.Choice1; }
    set { if (value) myChoice = MyChoices.Choice1; myChoiceChanged(); }
}

// and so on for the other two

private void myChoiceChanged()
{
    OnPropertyChanged(new PropertyChangedEventArgs("MyChoice_Choice1"));
    OnPropertyChanged(new PropertyChangedEventArgs("MyChoice_Choice2"));
    OnPropertyChanged(new PropertyChangedEventArgs("MyChoice_Choice3"));
}

then bind to MyChoice_Choice1 and the others?

Hayman answered 19/3, 2010 at 11:49 Comment(0)
S
0

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.

public enum MyChoices
{
    Choice1,
    Choice2,
    Choice3
}

public partial class Form1 : Form
{
    private Dictionary<int, RadioButton> radButtons;
    private MyChoices choices;

    public Form1()
    {
        this.InitializeComponent();
        this.radButtons = new Dictionary<int, RadioButton>();
        this.radButtons.Add(0, this.radioButton1);
        this.radButtons.Add(1, this.radioButton2);
        this.radButtons.Add(2, this.radioButton3);

        foreach (var item in this.radButtons)
        {
            item.Value.CheckedChanged += new EventHandler(RadioButton_CheckedChanged);
        }
    }

    private void RadioButton_CheckedChanged(object sender, EventArgs e)
    {
        RadioButton button = sender as RadioButton;
        foreach (var item in this.radButtons)
        {
            if (item.Value == button)
            {
                this.choices = (MyChoices)item.Key;
            }
        }
    }

    public MyChoices Choices
    {
        get { return this.choices; }
        set
        {
            this.choices = value;
            this.SelectRadioButton(value);
            this.OnPropertyChanged(new PropertyChangedEventArgs("Choices"));
        }
    }

    private void SelectRadioButton(MyChoices choiceID)
    {
        RadioButton button;
        this.radButtons.TryGetValue((int)choiceID, out button);
        button.Checked = true;
    }
}
Sanguine answered 20/3, 2010 at 7:17 Comment(0)
T
0

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:

public object this[string propertyName] { get; set; }

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.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Windows.Forms;
namespace Ezfx.Dui
{
    public static class RadioButtonGroupUI
    {
        public static void Apply(ApplicationSettingsBase settings, string key, Control parentControl)
        {
            List<RadioButton> radios = new List<RadioButton>();
            foreach(Control control in parentControl.Controls)
            {
                switch (control)
                {
                    case RadioButton e:
                        radios.Add(e);
                        break;
                }
            }

            Apply(settings, key, radios.ToArray());
        }

        public static void Apply(ApplicationSettingsBase settings, string key, params RadioButton[] radios)
        {

            foreach (RadioButton radioButton in radios)
            {
                if (radioButton.Text == (string)settings[key])
                {
                    radioButton.Checked = true;
                }

                radioButton.CheckedChanged += (sender, e) => {
                    if (radioButton.Checked)
                    {
                        settings[key] = radioButton.Text;
                    }
                    
                };
            }

            settings.PropertyChanged += (sender, e) =>
            {
                foreach (RadioButton radioButton in radios)
                {
                    if (radioButton.Text == (string)settings[key])
                    {
                        radioButton.Checked = true;
                    }
                    else
                    {
                        radioButton.Checked = false;
                    }
                }
            };
        }
    }
}

When using it. You simply add the following code in the form_load event.

    private void MainForm_Load(object sender, EventArgs e)
    {
        RadioButtonGroupUI.Apply(settings, "category", categoryGroupBox);
        RadioButtonGroupUI.Apply(settings, "package", scikitLearnRadioButton, sparkRadioButton);
    }

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.

Enum.TryParse(settings.category, out Category category);
Thingumabob answered 12/2, 2021 at 12:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.