我们平时自定义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 ox : TextBox
2.创建2个子控件的Style, 注意ControlTemplate中的子控件命名和上述属性声明一致
<Style TargetType="{x:Type local:}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:SearchBox}">
PART_SearchTextBox,PART_ClearButton及其它设置--------------->
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 = base.GetTemplateChild("PART_ClearButton") as Button; if (btnClear != null)
{ btnClear.Click += new RoutedEventHandler();
} } private void (Object sender, RoutedEventArgs e)
{ TextBox txtSearch = base.GetTemplateChild("PART_SearchTextBox") as TextBox; if (txtSearch!= null)
{ txtSearch.Text = String.Empty;
txtSearch.Focus();
} }
转载于:https://blog.51cto.com/muzizongheng/1332943