当前位置:  开发笔记 > 后端 > 正文

如何才能最好地处理WPF单选按钮?

如何解决《如何才能最好地处理WPF单选按钮?》经验,为你挑选了1个好方法。

我的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类型命令并编译错误,而不是在打字错误的情况下运行时错误.我怎样才能改善这个?



1> Ian Oakes..:

为了使命令起作用,您需要在xaml或后面的代码中设置绑定.这些命令绑定必须引用先前声明的公共静态字段.

然后在按钮Command属性中,您还需要引用这些相同的命令.


    
        
        
        
    
    
        One
        Two
        Three
    


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");
        }
    }
}

推荐阅读
小妖694_807
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有