zoukankan      html  css  js  c++  java
  • 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();
                }
            }
    
  • 相关阅读:
    AJAX请求 $.post方法的使用
    通过jQuery Ajax使用FormData对象上传文件
    iframe跨域访问
    js编码解码
    ajax头像上传
    无边框窗体和用户控件以及权限
    只开启一个窗体和进程以及多线程的操作
    通过一个窗体操作另一个窗体
    流和打印控件用法
    listview和简单的记事本操作
  • 原文地址:https://www.cnblogs.com/muzizongheng/p/3421336.html
Copyright © 2011-2022 走看看