Как лучше всего работать с переключателями WPF?

В моем XAML есть несколько RadioButton ...

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

И я могу обрабатывать их события щелчка в коде Visual Basic. Это работает...

    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

Но я бы хотел его улучшить. Этот код не работает ...

<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

В моем XAML я получаю синее волнистое подчеркивание атрибутов Command = и этот совет ...

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

В моем VB я получаю зеленое волнистое подчеркивание в строке Select Case, и это предупреждение ...

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

Еще лучше было бы использовать команды типа Enum с полным Intellisense и ошибки компиляции, а не ошибки времени выполнения в случае опечаток. Как я могу это улучшить?


person Zack Peterson    schedule 31.10.2008    source источник


Ответы (2)


Чтобы команды работали, вам необходимо настроить привязки либо в вашем xaml, либо в коде. Эти привязки команд должны ссылаться на публичные статические поля, которые были ранее объявлены.

Затем в атрибуте Command кнопок вам нужно будет также сослаться на эти же команды.

<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");
        }
    }
}
person Ian Oakes    schedule 31.10.2008
comment
Я использовал это, но когда я загружаю свою страницу, я не могу выбрать ни один из них. Есть ли способ включить выбор RadioButtons? - person paradisonoir; 15.07.2009
comment
Я не уверен, в чем может быть проблема, я только что запустил этот образец и смог выбрать переключатели нормально. - person Ian Oakes; 18.07.2009
comment
Если все радиокнопки отключены, я предполагаю, что привязки команд не смогли, э-э, привязать. - person Drew Noakes; 29.07.2009

Лучшее решение с использованием шаблона проектирования WPF MVVM.

Радиокнопка Control XAML для 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

Можно использовать ту же логику, указанную выше, чтобы увидеть, отметили ли вы какую-либо из трех радио-кнопок, а именно. Вариант первый, вариант второй, вариант третий. Но, проверяя, является ли логический набор id истинным или ложным, вы можете определить, установлен ли переключатель или нет.

person Sridhar Ganapathy    schedule 06.10.2016