处理键盘事件是应用系统中非常普遍的需求,通常我们需要处理KeyDown事件,并在事件中添加相应的代码。有时候我们需要处理控件内部处理过的事件,在 WPF/Silverlight/WinRT 平台中,我们可以通过 AddHandler 方法来监听事件处理。
比如以下代码:
public MainPage() { InitializeComponent(); this.gcSpreadSheet1.AddHandler(UIElement.KeyDownEvent, new KeyEventHandler(GcSpreadSheet_KeyDown), true); } private void GcSpreadSheet_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.C && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) { // 业务逻辑代码 } }
然而,通过这种方法控件还是会触发控件的行为,如何才能替换特定控件的键盘行为呢,Spread(for WPF/Silverlight/WinRT)中提供了一种灵活的自定义键盘行为的方法,通过这种方法可以替换控件内置的键盘事件逻辑,从而实现自定义的业务逻辑。
比如以下代码:
public MainPage() { InitializeComponent(); this.gcSpreadSheet1.View.KeyMap.Remove(new KeyStroke(Key.C, ModifierKeys.Control)); // remove build-in key mapping this.gcSpreadSheet1.View.KeyMap.Add(new KeyStroke(Key.C, ModifierKeys.Control), new SpreadAction(OnMyAction)); // map the key to your own action } private void OnMyAction(object sender, ActionEventArgs e) { // business logic code }
以上代码适用于Spread WPF/Silverlight和Spread WinRT中产品。