Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

Can't get accelerator key to work with WPF radio button

I am trying to assign a shortcut to a WPF radio button which is inside a grid which is inside a tab item. I tried simply using the underline character as shown which marks the label with an underline on the letter "F" but when sending the keys "Alt+f" it simply will not select the radio button.

    <RadioButton Name="DesktopRadioButtonFlags" Content="_Flags" HorizontalAlignment="Left" 
   Margin="39,39,0,0" Foreground="White" VerticalAlignment="Top" FlowDirection="RightToLeft"/>
question from:https://stackoverflow.com/questions/65643932/cant-get-accelerator-key-to-work-with-wpf-radio-button

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use input bindings

xaml

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

viewmodel

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

control or windows code to set ViewModel as DataContext (you should pass your initial data to windows or control constructor)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...