Как лучше всего использовать переключатели WPF?
У меня есть некоторые RadioButtons в моем 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>
И я могу обрабатывать свои события кликов в коде 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 я получаю синюю squiggly подчеркивание в атрибутах Command = и этом совете...
'CommandValueSerializer' ValueSerializer cannot convert from 'System.String'.
В моем VB я получаю зеленое короткое подчеркивание в строке Выбрать случай и это предупреждение...
Runtime errors might occur when converting 'System.Windows.Input.ICommand' to 'String'.
Еще лучше было бы использовать команды типа Enum с полными ошибками Intellisense и компиляции, а не ошибки времени выполнения в случае опечаток. Как я могу улучшить это?
Ответы
Ответ 1
Для того, чтобы команды работали, вам нужно настроить привязки либо в вашем xaml, либо в коде. Эти командные привязки должны ссылаться на общедоступные статические поля, которые были ранее объявлены.
Затем в ваших командных атрибутах Button вам также потребуется ссылаться на эти же команды.
<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");
}
}
}
Ответ 2
Лучшее решение с использованием шаблона проектирования WPF MVVM:
Кнопка управления радиостанцией 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 истинно или ложно, вы можете определить, включен ли переключатель или нет.