在WinForm时,可以定义一个基类继承自Form,从而在基类中重写和添加功能,要在WPF中实现类似方法要分为三步:
1. 自定义一个基类MyWindow继承自Window.
2. 将窗口的CS继承自MyWindow。
3. 在XAML中引用MyWindow命名空间,并在使用其别名自定义WPF窗口。
如下例重写Windows基类,自定义WPF窗口,实现改回车键为TAB:
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
<
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 >
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 >
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
public
partial
class
MainWindow : WindowsBase.DMSbase
{
public MainWindow()
{
InitializeComponent();
}
}
{
public MainWindow()
{
InitializeComponent();
}
}
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
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 }
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 }