重写Windows基类,自定义WPF窗口,实现改回车键为TAB

在WinForm时,可以定义一个基类继承自Form,从而在基类中重写和添加功能,要在WPF中实现类似方法要分为三步:

1. 自定义一个基类MyWindow继承自Window.

2.  将窗口的CS继承自MyWindow。

3. 在XAML中引用MyWindow命名空间,并在使用其别名自定义WPF窗口。

如下例重写Windows基类,自定义WPF窗口,实现改回车键为TAB:

XAML
<DecorationMS:DMSbase x:Class="DecorationMS.MainWindow"
xmlns:DecorationMS
="clr-namespace:DecorationMS.WindowsBase"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
Title
="TEST" Height="700" Width="1000">
<Grid Name="MainGrid">

</Grid>
</DecorationMS:DMSbase>
CS
public partial class MainWindow : WindowsBase.DMSbase
{
public MainWindow()
{
InitializeComponent();

}
}
自定义基类
1 using System.Windows;
2 using System.Windows.Input;
3
4 namespace DecorationMS.WindowsBase
5 {
6 public class DMSbase : Window
7 {
8 protected override void OnKeyDown(KeyEventArgs e)
9 {
10 if (e.Key == Key.Enter)
11 {
12 // MoveFocus takes a TraveralReqest as its argument.
13 TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);
14
15 // Gets the element with keyboard focus.
16 UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
17
18 // Change keyboard focus.
19 if (elementWithFocus != null)
20 {
21 elementWithFocus.MoveFocus(request);
22 }
23 e.Handled = true;
24 }
25 base.OnKeyDown(e);
26 }
27
28
29 }
30 }

posted @ 2011-02-19 22:31  Laro  阅读(1352)  评论(0编辑  收藏  举报