0

I want to allow the checking of radio buttons via the keyboard, specifically via the numbers 1, 2, 3. I've got this code that works:

// "a WPF form hears what it wants to hear and disregards the rest" - paraphrased from "The Boxer" by Simon & Garfunkel
private void Window_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs keArgs)
{
    var keyPressed = keArgs.Key.ToString();
    if ((keyPressed.Equals("D1")) || (keyPressed.Equals("NumPad1")))
    {
        rdbtnCandidateVal1.IsChecked = true;
    }
    else if ((keyPressed.Equals("D2")) || (keyPressed.Equals("NumPad2")))
    {
        rdbtnCandidateVal2.IsChecked = true;
    }
    else if ((keyPressed.Equals("D3")) || (keyPressed.Equals("NumPad3")))
    {
        rdbtnCandidateVal3.IsChecked = true;
    }
}

...but know this is kludgy'verbose. What is a better way to take action for a subset of keys and disregard the rest?

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • 1
    Those should be else if's seeing how if the first one is true you shouldn't have to bother with any of the other comparisons. I would say you could extract out a method, kind of like `CheckRadioButton(string[] acceptedKeys, RadioButton radioButton)` and do your logic in there. I guess that would make it look less "kludgy'verbose". – austin wernli Dec 12 '14 at 21:39
  • True; I updated the code above and the real code. – B. Clay Shannon-B. Crow Raven Dec 12 '14 at 21:43
  • 2
    @austinwernli, good suggestion for the If/Else change, but my first coding instructor suggested using case statements when I need more than two If conditions. – jac Dec 12 '14 at 21:46
  • 1
    What about a custom RadioButton control class that maybe has a property string[] of acceptedKeys? Last idea i'm throwing out there ha – austin wernli Dec 12 '14 at 21:58

0 Answers0