WPF案例:如何设计搜索框(自定义控件的原则和方法)

我们平时自定义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();
             }         } 

你可能感兴趣的:(template,案例,WPF,自我心的,SearchBox)