我的XAML中有一些RadioButton ...
One Two Three
我可以在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
但是,我想改进它.这段代码失败了......
One Two Three
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'.
更好的方法是使用具有完整Intellisense的Enum类型命令并编译错误,而不是在打字错误的情况下运行时错误.我怎样才能改善这个?
为了使命令起作用,您需要在xaml或后面的代码中设置绑定.这些命令绑定必须引用先前声明的公共静态字段.
然后在按钮Command属性中,您还需要引用这些相同的命令.
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"); } } } One Two Three