Как я могу снять флажки с радиокнопок в C #, оставляя только первую радиокнопку для вкладок? - PullRequest
1 голос
/ 03 ноября 2019

Не уверен, имеет ли название смысл, поэтому вот полный контекст:

Я пишу код на C #. Я сделал приложение с несколькими пользовательскими элементами управления, в каждом из которых много текстовых полей и радиокнопок. Все радиокнопки располагаются на панели в наборе из 2, что выглядит следующим образом:

[ <label> O <radiobutton1text> O <radiobutton2text> ]

(в то время как первая радиокнопка имеет TabStop = true, а вторая TabStop = false)

При переходе на такую ​​панель фокусируется только текст radiobutton1, а при нажатии клавиши со стрелкой влево выбирается текст radiobutton2. Это желаемый результат.

Чтобы ускорить загрузку UserControl во второй (и выше) раз, я не закрываю его, а заменяю его другим UserControl каждый раз, когда необходимо изменить содержимое. Но возникает проблема: когда открыт UserControl X, затем поверх него я открываю UserControl Y и затем возвращаюсь к X, текстовые поля и радиокнопки по-прежнему содержат содержимое с первого сеанса, когда у меня впервые был открыт UserControl X,(Мне необходимо сбросить содержимое текстовых полей и радиокнопок после замены UserControl).

Поэтому я создал функцию, которая перебирает все элементы управления и очищает их содержимое. Проблема в том, что когда я снимаю флажок с радиокнопок (и возвращаю им состояние TabStop в true), вторая радиокнопка становится вкладкой после того, как я проверяю одну из них и затем вызываю функцию, тогда как она не былаt перед выполнением этой функции.

Функция:

        public void BackToMain(object sender, EventArgs e)
        {
            // Go through all controls and empty each TextBox, RichTextBox, RadioButton or ComboBox.
            int parentControlsCount = Controls.Count - 1;
            for (int i = parentControlsCount; i >= 0; i--)
            {
                if (Controls[i].HasChildren == true)
                {
                    int childrenControlsCount = Controls[i].Controls.Count - 1;
                    for (int j = childrenControlsCount; j >= 0; j--)
                    {
                        var controlType = Controls[i].Controls[j].GetType().ToString();

                        switch (controlType)
                        {
                            case "System.Windows.Forms.TextBox":
                            case "System.Windows.Forms.RichTextBox":
                                Controls[i].Controls[j].Text = null;
                                break;

                            case "System.Windows.Forms.RadioButton":
                                // Restore both properties to default value
                                ((RadioButton)Controls[i].Controls[j]).Checked = false;
                                if (j == 1)
                                    ((RadioButton)Controls[i].Controls[j]).TabStop = true;
                                else if (j == 2)
                                    ((RadioButton)Controls[i].Controls[j]).TabStop = false;
                                break;

                            case "System.Windows.Forms.ComboBox":
                                ((ComboBox)Controls[i].Controls[j]).SelectedIndex = -1;
                                break;
                        }
                    }
                }
            }
        }

Что я делаю не так?

1 Ответ

0 голосов
/ 05 ноября 2019

Я закончил тем, что применил эту грубую хакерскую функцию к каждой второй кнопке CheckedChange для радиокнопки:

        private void DisableTabStopOnCheckedChange(object sender, EventArgs e)
        {
            // Assume the following STR:
            // 1. In any radiobutton panel, select any radiobutton (without ever invoking BackToMain function in the first post);
            // 2. Invoke the BackToMain function;
            // 3. In the same radiobutton panel as in step #1, click the second radiobutton.
            // Normally, without this function, if the user will now cycle through the controls using the Tab key, both the first and second radiobuttons will be tabbable,
            // and that's because in the BackToMain function we reset their Checked and TabStop properies, and that's something that should be handled automatically by the control itself.
            // Doing it manually means that for the *first time* selecting the second radiobutton, the first one's TabStop state won't update, which means both radiobuttons
            // will have the TabStop state set to true, causing both to be tabbable.
            // This is a gross hack to fix this by disabling TabStop on the first radio button if the second one is checked and the first one's TabStop state
            // is true (this should happen only after BackToMain has been invoked).
            if (((RadioButton)sender).Checked)
            {
                var firstRadioButton = ((RadioButton)sender).Parent.Controls[1];
                if (((RadioButton)firstRadioButton).TabStop == true)
                {
                    ((RadioButton)firstRadioButton).TabStop = false;
                }
            }
        }

Я знаю, что это не очень хорошее решение. Но это работает.

...