16p*_*er9 5 c# xaml keyboard-shortcuts
我有一个软件,它为不同的实例使用多个XAML窗口:例如,为了导出一些信息,我创建了与母软件格式不同的辅助XAML窗口.他们工作正常.
我的问题是,如果我在不调用任何这些辅助XAML窗口的情况下使用我的软件,则快捷方式可以很好地工作.但是,只要我调用这个新的XAML窗口,快捷方式就不再起作用了.我需要重新启动程序才能让它们恢复活力.
有关这种行为的任何线索?另外,我还没有能够创建像CTRL + Letter这样的快捷方式.我见过很多代码,看起来很简单,但它们只是不起作用......
码
private void Window_KeyDown(object sender, KeyEventArgs e)
{
Key key = e.Key;
if ((key == Key.Left) && previousButton.IsEnabled)
button_PreviewMouseDown(previousButton, null);
else if ((key == Key.Right) && nextButton.IsEnabled)
button_PreviewMouseDown(nextButton, null);
//New Label
else if (key == Key.L)
//else if (key == Key.LeftAlt && e.Key.ToString() == "L")
NewLabel_Click(sender, e);
// Begin Event
else if (key == Key.B)
BeginEvent_Click(sender, e);
// End Event
else if (key == Key.E)
EndEvent_Click(sender, e);
// Delete Label
else if (key == Key.K)
DeleteLabel_Click(sender, e);
else if (key == Key.R)
// Delete Event
DeleteEvent_Click(sender, e);
// Edit Label
else if (key == Key.I)
EditLabel_Click(sender, e);
// Edit Event
else if (key == Key.F)
EditEvent_Click(sender, e);
}
Run Code Online (Sandbox Code Playgroud)
编辑1
我现在发现,只要我打电话给C#弹出消息框,只是说"事件创建好了",快捷方式再次活跃起来!
MessageBox.Show("Event Created");
Run Code Online (Sandbox Code Playgroud)
知道为什么会这样吗?
另一种方法是使用RoutedCommands。使用 RoutedCommand 您可以分配KeyGestures。
例子
/// <summary>
/// Save Log command
/// </summary>
public static readonly RoutedCommand SaveLog =
new RoutedCommand("SaveLog", typeof(Commands),
new InputGestureCollection
{
new KeyGesture(Key.S, ModifierKeys.Control,"Save log contents to a file. (Ctl+S)")
});
Run Code Online (Sandbox Code Playgroud)
在 xaml 中分配 RoutedCommand
<Button Style="{StaticResource LoggingWindowSaveLogButton}" Command ="{x:Static local:Commands.SaveLog}" />
Run Code Online (Sandbox Code Playgroud)
将命令绑定到您的窗口
<!-- Command Bindings-->
<Window.CommandBindings>
<CommandBinding Command="{x:Static local:Commands.SaveLog}" Executed="SaveLogCommand" CanExecute="SaveLogCommandCanExecute"/>
</Window.CommandBindings>
Run Code Online (Sandbox Code Playgroud)
然后实现SaveLogCommandCanExecute和SaveLogCommand
如果 SaveLogCommandCanExecute 返回false,它将自动禁用 RoutedCommand 绑定到的任何 GUI。
请记住,具有键绑定的窗口必须具有焦点。