首页 > 解决方案 > 无法让加速键与 WPF 单选按钮一起使用

问题描述

我正在尝试为 WPF 单选按钮分配一个快捷方式,该按钮位于选项卡项内的网格内。我尝试简单地使用下划线字符,如图所示,它在字母“F”上用下划线标记标签,但是当发送键“Alt+f”时,它根本不会选择单选按钮。

    <RadioButton Name="DesktopRadioButtonFlags" Content="_Flags" HorizontalAlignment="Left" 
   Margin="39,39,0,0" Foreground="White" VerticalAlignment="Top" FlowDirection="RightToLeft"/>

标签: wpf

解决方案


您应该使用输入绑定

xml

<Window.InputBindings>
    <KeyBinding Modifiers="Alt" Key="F" Command="{Binding CheckRadioButton1Command}"/>
</Window.InputBindings>
<Grid>
    <RadioButton Content="_Flags" IsChecked="{Binding IsRadioChecked}"/>
</Grid>

视图模型

public class MyViewModel : INotifyPropertyChanged
{
    private bool _isRadioChecked;
    public bool IsRadioChecked
    {
        get => _isRadioChecked;
        set
        {
            if (_isRadioChecked == value)
                return;

            _isRadioChecked = value;
            OnPropertyChanged(nameof(IsRadioChecked));
        }
    }

    private ICommand _checkRadioButton1Command;
    public ICommand CheckRadioButton1Command => _checkRadioButton1Command ?? (_checkRadioButton1Command = new ActionCommand(CheckRadioButton1));

    private void CheckRadioButton1()
    {
        IsRadioChecked = true;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

将 ViewModel 设置为 DataContext 的控件或 windows 代码(您应该将初始数据传递给 windows 或控件构造函数)

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MyViewModel();
    }
}

推荐阅读