I've got some RadioButtons in my XAML…
<StackPanel>
<RadioButton Name="RadioButton1" GroupName="Buttons" Click="ButtonsChecked" IsChecked="True">One</RadioButton>
<RadioButton Name="RadioButton2" GroupName="Buttons" Click="ButtonsChecked">Two</RadioButton>
<RadioButton Name="RadioButton3" GroupName="Buttons" Click="ButtonsChecked">Three</RadioButton>
</StackPanel>
And I can handle their click events in the Visual Basic code. This works…
Private Sub ButtonsChecked(ByVal sender As System.Object, _ ByVal e As System.Windows.RoutedEventArgs) Select Case CType(sender, RadioButton).Name Case "RadioButton1" 'Do something one Exit Select Case "RadioButton2" 'Do something two Exit Select Case "RadioButton3" 'Do something three Exit Select End Select End Sub
But, I'd like to improve it. This code fails…
<StackPanel>
<RadioButton Name="RadioButton1" GroupName="Buttons" Click="ButtonsChecked" Command="one" IsChecked="True">One</RadioButton>
<RadioButton Name="RadioButton2" GroupName="Buttons" Click="ButtonsChecked" Command="two">Two</RadioButton>
<RadioButton Name="RadioButton3" GroupName="Buttons" Click="ButtonsChecked" Command="three">Three</RadioButton>
</StackPanel>
Private Sub ButtonsChecked(ByVal sender As System.Object, _ ByVal e As System.Windows.RoutedEventArgs) Select Case CType(sender, RadioButton).Command Case "one" 'Do something one Exit Select Case "two" 'Do something two Exit Select Case "three" 'Do something three Exit Select End Select End Sub
In my XAML I get a blue squiggly underline on the Command= attributes and this tip…
'CommandValueSerializer' ValueSerializer cannot convert from 'System.String'.
In my VB I get a green squiggly underline on the Select Case line and this warning…
Runtime errors might occur when converting 'System.Windows.Input.ICommand' to 'String'.
Even better would be to use Enum type commands with full Intellisense and compile errors rather than runtime errors in case of typos. How can I improve this?
Best Answer
In order for commands to work you need to set up bindings in either your xaml or code behind. These command bindings must reference public static fields that have been previously declared.
Then in your buttons Command attribute you will then need to also reference these same commands.