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();
             }         } 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章