快捷方式有問題,任何幫助/提示將不勝感激! 目標:我需要能夠處理快捷鍵,在我的應用程序中有和沒有修飾符。 因此,例如我需要處理關鍵字'a'以及'CTR + a'。但是我只想在沒有控制權處理這些鍵時處理它們。例如TextBox類需要大多數鍵,包括一些命令,如'Ctrl + C'等,所以我不想在TextBox處理它們時攔截這些事件。如何正確處理快捷鍵和鍵盤事件?
我嘗試使用命令以及將事件附加到窗口的KeyUp,但是,在文本框獲取機會查看它們之前,命令攔截鍵,即使TextBox使用該鍵,KeyDown泡泡到窗口級別!我怎樣才能讓我的窗口獲得不被任何子控件處理的密鑰?請參閱下面的代碼,這對我無效。另外,由於我有很多不同的控件,我寧願有一個「適當的」解決方案:我寧願不把處理程序附加到窗口中的每個控件實例上。
<Window x:Class="KeyTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.CommandBindings>
<CommandBinding Command="Help"
CanExecute="HelpCanExecute"
Executed="HelpExecuted" />
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Command="Help" Key="H" />
</Window.InputBindings>
<Grid>
<WrapPanel>
<TextBox Name="myLOG" Width="300" Height="200" Background="LightBlue" />
<TextBox Name="myINPUT" Width="300" Height="200" />
<Button Content="JUST FOR FUN" />
</WrapPanel>
</Grid>
而對於C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace KeyTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private void HelpCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
myLOG.Text += "HELP CAN EXECUTE\n";
e.CanExecute = true;
e.Handled = true;
}
private void HelpExecuted(object sender, ExecutedRoutedEventArgs e)
{
myLOG.Text += "HELP EXECUTED!!!\n";
e.Handled = true;
}
public void myKeyUpHandler(Object sender, KeyEventArgs args)
{
myLOG.Text += "KEY UP EVENT! " + args.Key + "\n";
}
public MainWindow()
{
InitializeComponent();
this.KeyUp += new KeyEventHandler(myKeyUpHandler);
}
}
}
當焦點在文本框中,按下 「H」 觸發命令,即使我想 'H' 只去文框。此外,當文本框內,按任何字母數字鍵觸發KeyUp事件,即使據我所知,文本框應該已處理=真的事件!
感謝您的幫助!
+1給你這是一個真正有用的問題,可以作爲WPF初學者的參考。 – 2011-12-16 01:23:10