1

I'm having difficulty with something which seems like it should be very simple. I'm coming from Windows Forms and starting up with WPF. I think I have a simple syntax issue but I can't seem to find a specific example for this radio button issue.

I have a radio button on my GUI for a query to run either via a map selection or a list. When load is clicked, it should perform one operation if map is selected, a different operation for list. Code looks similar to this:

private void Load_Click(object sender, RoutedEventArgs e)
{
  if (rdBtnList.Checked == true)
  {
    //do this
  }

  // if rdBtnList not checked (ie if rdBtnMap is checked)
  // do this
}

Any help would be greatly appreciated. Thanks.

Metro Smurf
  • 37,266
  • 20
  • 108
  • 140
Nallware
  • 159
  • 1
  • 4
  • 18

3 Answers3

7

Change:

if (rdBtnList.Checked == true)

to

if (rdBtnList.IsChecked == true)

Note:

I'm coming from Windows Forms and starting up with WPF

  • You must forget everything you ever learned in winforms, and embrace MVVM. You should create a ViewModel and bind your rdBtnList.IsChecked property to some boolean value in the ViewModel, then perform your logic in there. The views' code behind is not the right place for application logic.
Federico Berasategui
  • 43,562
  • 11
  • 100
  • 154
  • Its difficult to forget everything about Windows Forms. I'm having to utilize Forms for some things also (not necessarily by my choice). – Nallware Mar 25 '13 at 16:52
  • 1
    @nallware once you realize how simple everything is in MVVM, you'll never want to go `back` to winforms. – Federico Berasategui Mar 25 '13 at 16:54
  • Yeah, I think I'll agree by default, but when you're told "do it this way" you "do it this way". *shrugs* – Nallware Mar 25 '13 at 20:02
1

The property in WPF is called IsChecked hence you just need to update the if statement

if (rdBtnList.IsChecked == true) { 
  ...
}

The IsChecked property is bool? (nullable value) in WPF so you may choose to be more explicit here by doing the following

if (rdBtnList.IsChecked.HasValue && rdBtnList.IsChecked.Value) { 
  ...
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0

Are you missing a return statement? As is, the posted code will always execute the if not checked path:

private void Load_Click(object sender, RoutedEventArgs e)
{
  if (rdBtnList.IsChecked == true)
  {
    //do this
    return; // return, or the if not checked path below will always win.
  }

  // if rdBtnList not checked (ie if rdBtnMap is checked)
  // do this
}

In WPF, you'll need to use the IsChecked property. See the RadioButton Class for more details.

Metro Smurf
  • 37,266
  • 20
  • 108
  • 140