Winforms связывают перечисление с переключателями

Если у меня есть три переключателя, что лучший способ состоит в том, чтобы связать их с перечислением, которое имеет тот же выбор? например.

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

public enum MyChoices
{
    Choice1,
    Choice2,
    Choice3
}
7
задан Damien 19 March 2010 в 11:44
поделиться

2 ответа

Не могли бы вы создать три логических свойства :

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

затем привязать к MyChoice_Choice1 и другим?

2
ответ дан 7 December 2019 в 09:59
поделиться

Я просто решил добавить способ, которым я сейчас это делаю. Здесь нет "привязки" как таковой, но, надеюсь, это делает ту же работу.

Комментарии приветствуются.

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;
    }
}
0
ответ дан 7 December 2019 в 09:59
поделиться
Другие вопросы по тегам:

Похожие вопросы: