我的命令KeyGesture仅在我单击按钮后才起作用

问题描述 投票:0回答:1

我有一个“打开项目”按钮,单击该按钮会打开一个文件对话框并允许用户选择一个文件。我添加了一个命令,以便用户还可以使用“Ctrl + O”来选择文件。

问题是,当我第一次运行应用程序时,如果我还没有单击按钮,则 KeyGesture 将不会打开文件对话框,但如果我单击按钮并关闭文件对话框,则“Ctrl + O”然后有效。

这是我的xaml中的代码:

    <UserControl.CommandBindings>
        CommandBinding Command="local:ButtonCommands.OpenProject"    CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed"/>
</UserControl.CommandBindings>

这是我的 ButtonsCommand 类:

公共静态 RoutedUICommand OpenProject { get;放; }

static ButtonCommands()
{
    InputGestureCollection input = new InputGestureCollection();
    KeyGesture shortkey = new KeyGesture(Key.O, ModifierKeys.Control);
    input.Add(shortkey);

    OpenProject = new RoutedUICommand("Open Project", "OpenProject", typeof(ButtonCommands), input);
}

这是我的视图代码:

public void btnOpenFile_Click(object sender, RoutedEventArgs e)
{
    if (Command != null)
    {
        if (Command.CanExecute(CommandParameter))
        {
            Command.Execute(CommandParameter);
        }
    }            
}
private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = true;
}
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
    OpenFileDialog openFileDialog = new OpenFileDialog();
    openFileDialog.Filter = "Aztec files (*.oipx) |*.oipx";
    if (openFileDialog.ShowDialog() == true)
    {
        ProjectDataProvider.Instance.OpenDBandGetData(openFileDialog.FileName);
    }
}
c# wpf mvvm command
1个回答
0
投票

尝试检查一下

    private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    // Check if the button is focused
    e.CanExecute = btnOpenFile.IsKeyboardFocusWithin;
}

或您要检查

<Button Command="local:ButtonCommands.OpenProject" Click="btnOpenFile_Click">Open Project</Button>
© www.soinside.com 2019 - 2024. All rights reserved.