我们平时自定义WPF控件的方法有:Style,DataTemplate,ControlTemplate, DependencyProperty, CustomControl等几个方法。

按照优先顺序应该是从左到右。(所谓Style,这里仅包括Setter)
对于搜索框,其组成也就是TextBox+Button(清空),这里我们用CustomControl的方法比较合适。
1.创建SearchBox继承于TextBox,并声明2个Part属性, 表明此控件组成
     [TemplatePart(Name = "PART_SearchTextBox", Type = typeof(TextBox))]
     [TemplatePart(Name = "PART_ClearButton", Type = typeof(Button))]
      public class SearchBox : TextBox
2.创建2个子控件的Style, 注意ControlTemplate中的子控件命名和上述属性声明一致
<Style TargetType="{x:Type local:SearchBox}">
      <Setter Property="Template">   
         <Setter.Value>                
               <ControlTemplate TargetType="{x:Type local:SearchBox}">
                    <!-------------子控件PART_SearchTextBox,PART_ClearButton及其它设置--------------->
               </ControlTemplate>
          </Setter.Value>
      </Setter>
</Style>
3.如果在当前程序集里,必须放在.\Themes文件夹下; 必须在程序集的AssemblyInfo.cs里指定ThemeInfo(用来指定控件默认Style)
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
4.在自定义控件的实现中注册路由事件等等其它逻辑处理
比如:对子元素Clear按钮进行处理
       public override void OnApplyTemplate()
        {
base.OnApplyTemplate(); Button btnClear = base.GetTemplateChild("PART_ClearButton") as Button;
if (btnClear != null)
            {
btnClear.Click += new RoutedEventHandler(OnClearButton_Click);
            }
} private void OnClearButton_Click(Object sender, RoutedEventArgs e)
        {
TextBox txtSearch = base.GetTemplateChild("PART_SearchTextBox") as TextBox; if (txtSearch!= null)
            {
txtSearch.Text = String.Empty;
               txtSearch.Focus();
            }
}

最新文章

  1. 浅谈js命名空间管理
  2. Topcoder SRM 683 Div2 B
  3. NC 查询公司下所分配的组织,并存放字符串数组中
  4. linux core dump 文件 gdb分析
  5. 【cs229-Lecture19】微分动态规划
  6. java 异常处理 Throwable Error 和Exception
  7. BZOJ 1257 余数之和sum
  8. libevent使用
  9. Android自己定义控件:老版优酷的三级菜单(效果图 + Demo)
  10. IntelliSense 无法仅由函数的返回类型重装分辨
  11. 【CF715E】Complete the Permutations 第一类斯特林数
  12. Linux文件与目录管理(学习笔记)
  13. Java Statement PK PrepareStatement
  14. PAT L2-013 红色警报
  15. Windows配置Apache服务器
  16. Centos安装Grafana
  17. docker --swarm启动2375端口监听
  18. go语言学习之路(一)Hello World
  19. 快速沃尔什变换与k进制FWT
  20. 元素加了position:absolute则该元素的text-align:center居中失效的解决办法

热门文章

  1. linux驱动的异步通知(kill_fasync,fasync)---- 驱动程序向应用程序发送信号
  2. DNS 主从同步配置
  3. @MarkFan 口语练习录音 20140415 [MDL演讲口语录音]
  4. Xamarin简介与Xamarin支持MVC设计模式
  5. 20145222黄亚奇 《网络对抗技术》 MAL_逆向与Bof基础
  6. 在IOS开发中,项目的目录结构如何搭建?
  7. 吴恩达深度学习笔记(九) —— FaceNet
  8. 生成一个ipa的包,使非开发机也能安装成功 (Xcode5.1)
  9. PAT1023. Have Fun with Numbers (20)
  10. ANT+JMETER集成2 (发送邮件)