2008-10-31 11 views
11

Tengo algunas RadioButtons en mi XAML ...¿Cómo puedo manejar mejor los botones de radio WPF?

<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> 

Y puede manejar sus eventos de clic en el código de Visual Basic. Esto funciona ...

 
    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 

Pero me gustaría mejorarlo. Este código falla ...

<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 

En mi XAML consigo un Subrayado azul ondulada en los Command = atributos y este consejo ...

'CommandValueSerializer' ValueSerializer cannot convert from 'System.String'.

En mi VB consigo un subrayado ondulado verde en la línea Select Case y esta advertencia ...

Runtime errors might occur when converting 'System.Windows.Input.ICommand' to 'String'.

Sería aún mejor utilizar comandos de tipo Enum con Intellisense completo y errores de compilación en lugar de errores de tiempo de ejecución en caso de errores tipográficos. ¿Cómo puedo mejorar esto?

Respuesta

18

Para que los comandos funcionen, necesita configurar enlaces tanto en su xaml como en su código. Estos enlaces de comando deben hacer referencia a los campos públicos estáticos que se han declarado previamente.

Luego, en sus botones Comando de atributo, necesitará también hacer referencia a estos mismos comandos.

<Window 
    x:Class="RadioButtonCommandSample.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:RadioButtonCommandSample" 
    Title="Window1" 
    Height="300" 
    Width="300" 
    > 
    <Window.CommandBindings> 
     <CommandBinding Command="{x:Static local:Window1.CommandOne}" Executed="CommandBinding_Executed"/> 
     <CommandBinding Command="{x:Static local:Window1.CommandTwo}" Executed="CommandBinding_Executed"/> 
     <CommandBinding Command="{x:Static local:Window1.CommandThree}" Executed="CommandBinding_Executed"/> 
    </Window.CommandBindings> 
    <StackPanel> 
     <RadioButton Name="RadioButton1" GroupName="Buttons" Command="{x:Static local:Window1.CommandOne}" IsChecked="True">One</RadioButton> 
     <RadioButton Name="RadioButton2" GroupName="Buttons" Command="{x:Static local:Window1.CommandTwo}">Two</RadioButton> 
     <RadioButton Name="RadioButton3" GroupName="Buttons" Command="{x:Static local:Window1.CommandThree}">Three</RadioButton> 
    </StackPanel> 
</Window> 

public partial class Window1 : Window 
{ 
    public static readonly RoutedCommand CommandOne = new RoutedCommand(); 
    public static readonly RoutedCommand CommandTwo = new RoutedCommand(); 
    public static readonly RoutedCommand CommandThree = new RoutedCommand(); 

    public Window1() 
    { 
     InitializeComponent(); 
    } 

    private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) 
    { 
     if (e.Command == CommandOne) 
     { 
      MessageBox.Show("CommandOne"); 
     } 
     else if (e.Command == CommandTwo) 
     { 
      MessageBox.Show("CommandTwo"); 
     } 
     else if (e.Command == CommandThree) 
     { 
      MessageBox.Show("CommandThree"); 
     } 
    } 
} 
+0

Lo usé, pero cuando cargo mi página, no puedo seleccionar ninguna de ellas. ¿Hay alguna forma de habilitar la selección de RadioButtons? – paradisonoir

+0

No estoy seguro de cuál podría ser el problema, simplemente ejecuté esta muestra y pude seleccionar los botones de radio de forma correcta. –

+0

Si todos los botones de radio están deshabilitados, entonces supongo que los enlaces de comando no pudieron, er, obligar. –

0

solución mejor usando WPF MVVM Diseño Patrón:

control de radio Botón XAML a Modelview.vb/ModelView.cs:

XAML Code: 
<RadioButton Content="On" IsEnabled="True" IsChecked="{Binding OnJob}"/> 
<RadioButton Content="Off" IsEnabled="True" IsChecked="{Binding OffJob}"/> 

ViewModel.vb:

Private _OffJob As Boolean = False 
Private _OnJob As Boolean = False 

Public Property OnJob As Boolean 
    Get 
     Return _OnJob 
    End Get 
    Set(value As Boolean) 
     Me._OnJob = value 
    End Set 
End Property 

Public Property OffJob As Boolean 
    Get 
     Return _OffJob 
    End Get 
    Set(value As Boolean) 
     Me._OffJob = value 
    End Set 
End Property 

Private Sub FindCheckedItem() 
    If(Me.OnJob = True) 
    MessageBox.show("You have checked On") 
End If 
If(Me.OffJob = False) 
MessageBox.Show("You have checked Off") 
End sub 

Uno puede usar la misma lógica de arriba para ver si marcó un ny de los tres Radio Botones a saber. Opción uno, opción dos, opción tres. Pero si comprueba si el valor booleano es verdadero o falso, puede identificar si el botón de opción está marcado o no.

Cuestiones relacionadas