WPF案例:如何设计搜索框(自定义控件的原则和方法)
2013-11-13 14:18
351 查看
我们平时自定义WPF控件的方法有:Style,DataTemplate,ControlTemplate, DependencyProperty, CustomControl等几个方法。 按照优先顺序应该是从左到右。(所谓Style,这里仅包括Setter)
对于搜索框,其组成也就是TextBox+Button(清空),这里我们用CustomControl的方法比较合适。
1.创建SearchBox继承于TextBox,并声明2个Part属性, 表明此控件组成
对于搜索框,其组成也就是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();
} }本文出自 “木子纵横” 博客,请务必保留此出处http://muzizongheng.blog.51cto.com/856912/1332943
相关文章推荐
- WPF案例:如何设计搜索框(自定义控件的原则和方法)
- WPF案例:如何设计搜索框(自定义控件的原则和方法)
- WPF案例:如何设计历史记录查看UI
- WPF案例:如何设计历史记录查看UI
- WPF案例:如何设计历史记录查看UI
- Jquery如何序列化form表单数据为JSON对象 C# ADO.NET中设置Like模糊查询的参数 从客户端出现小于等于公式符号引发检测到有潜在危险的Request.Form 值 jquery调用iframe里面的方法 Js根据Ip地址自动判断是哪个城市 【我们一起写框架】MVVM的WPF框架(三)—数据控件 设计模式之简单工厂模式(C#语言描述)
- 面向对象六大原则和23中设计模式 , 以及记忆方法
- 如何设计PHP业务模块(函数/方法)返回结果的结构?
- 20+案例教你可视化图表的设计方法!
- java基础七(成员变量 局部变量 匿名对象 封装 设计原则 private this 构造方法 static)
- 设计原则:如何应对模型的复杂性 之 更细粒度的组织命名空间
- 表设计的原则与方法分析:追求表价值的最大化
- 简单干净的C#方法设计案例:SFCUI.AjaxLoadPage()之一
- 数据库表结构设计方法及原则
- 如何建立一个网站?规划、设计、目的、原则、宣传(转)
- 方法接口UML统一建模语言,java中七种设计原则,
- 浅谈如何设计更好的java方法
- 如何让设计器不生成自定义控件属性的代码
- 如何设计接口原则?
- 数据库三大范式详解(转载、含数据库设计原则与方法链接)