项目中可能会遇到重写控件的情况,特此记录下:

 1 <window x:class="wpfapp6.mainwindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 5         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 6         xmlns:local="clr-namespace:wpfapp6"
 7         mc:ignorable="d"
 8         title="mainwindow" height="157" width="287">
 9     <window.resources>
10         <style targettype="local:customtextbox">
11             <setter property="template">
12                 <setter.value>
13                     <controltemplate>
14                         <grid>
15                             <grid.columndefinitions>
16                                 <columndefinition />
17                                 <columndefinition width="auto" />
18                             </grid.columndefinitions>
19                             <textbox verticalcontentalignment="center" 
20                                      padding="5"
21                                      text="{binding relativesource={relativesource templatedparent},path=text}"/>
22                             <button x:name="btnclear" grid.column="1" width="30" margin="3" content="清空" />
23                         </grid>
24                     </controltemplate>
25                 </setter.value>
26             </setter>
27         </style>
28     </window.resources>
29     <grid>
30         <stackpanel>
31             <local:customtextbox text="852"/>
32         </stackpanel>
33     </grid>
34 </window>
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading.tasks;
 6 using system.windows;
 7 using system.windows.controls;
 8 using system.windows.data;
 9 using system.windows.documents;
10 using system.windows.input;
11 using system.windows.media;
12 using system.windows.media.imaging;
13 using system.windows.navigation;
14 using system.windows.shapes;
15 
16 namespace wpfapp6
17 {
18     /// <summary>
19     /// mainwindow.xaml 的交互逻辑
20     /// </summary>
21     public partial class mainwindow : window
22     {
23         public mainwindow()
24         {
25             initializecomponent();
26         }
27     }
28 
29 
30     public class customtextbox : textbox
31     {
32         public override void onapplytemplate()
33         {
34             base.onapplytemplate();
35 
36             var btnclear = gettemplatechild("btnclear") as button;
37             btnclear.click += btnclear_click;
38         }
39 
40         private void btnclear_click(object sender, routedeventargs e)
41         {
42             text = string.empty;
43         }
44     }
45 }