且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我怎样才能***地处理WPF单选按钮?

更新时间:2022-02-14 00:36:58

为了让命令工作,你需要设置绑定在任何您的XAML或code后面。这些命令绑定必须引用已经previously声明公共静态字段。

In order for commands to work you need to set up bindings in either your xaml or code behind. These command bindings must reference public static fields that have been previously declared.

然后在你的按钮命令属性,那么你将还需要引用这些相同的命令。

Then in your buttons Command attribute you will then need to also reference these same commands.

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