WPF自动完成控件

代码:/Files/zhuqil/AutoComplete.zip

WPF自动完成控件

介绍:

     在WPF中缺少一个支持自动完成的控件,最接近的控件是ComboBox ,它也是实现本篇文章的一个基础控件。

背景:

     一个自动完成控件允许用户输入文本的时候,控件会尽可能的去查询出一个用户已经输入的文本选择项。最流行的自动完成处理是通过查询这个控件当前文本的开头部分。

它是如何运作:

下面是我们关心的一些ComboBox中的属性:
  • IsEditable- 这个允许用户在这个控件上输入文本。
  • StaysOpenOnEdit - 这个将强制ComboBox在输入时保持打开。
  • IsTextSearchEnabled - 这将使用ComboBox默认的自动完成的行为。
  •  

    我们通过使用上面的属性结合一个控制延迟查询的时间,和允许用户附加新的数据源的事件,以及一些风格样式,来实现自动完成控件(AutoComplete.xaml.cs文件中)

     

    使用这个控件

     

    < Window  x:Class ="Gui.TestWindow"
        xmlns
    ="http://schemas.microsoft.com/winfx/2006/xaml/sentation"
        xmlns:x
    ="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ctr
    ="clr-namespace:Gui.Controls"
          Title
    ="Auto Complete Test"  
          Height
    ="200"  Width ="300"  
          Loaded
    ="Window_Loaded" >
        
    < StackPanel >
            
    < StackPanel.Resources >
                
    < ResourceDictionary 
                  
    Source ="/Gui.Controls;component/Styles/AutoComplete.Styles.xaml"   />
            
    </ StackPanel.Resources >
            
            
    < Label > Cities: </ Label >
            
    < ctr:AutoComplete  x:Name ="autoCities"  
               SelectedValuePath
    ="CityID"  DisplayMemberPath ="Name"  
               PatternChanged
    ="autoCities_PatternChanged"  
               Style
    =" {StaticResource AutoCompleteComboBox} "
               Delay
    ="500" />  
            
    <!--  can also do binding on selected value  -->
        
    </ StackPanel >
    </ Window >

     

    类似一个combobox,自动完成控件利用 DisplayMemberPath 和 SelectValuePath 属性来绑定具体的数据源
    ///   <summary>
    ///  occurs when the user stops typing after a delayed timespan
    ///   </summary>
    ///   <param name="sender"></param>
    ///   <param name="args"></param>
    protected   void  autoCities_PatternChanged( object  sender, 
              Gui.Controls.AutoComplete.AutoCompleteArgs args)
    {
        
    // check
         if  ( string .IsNullOrEmpty(args.Pattern))
            args.CancelBinding 
    =   true ;
        
    else
            args.DataSource 
    =  TestWindow.GetCities(args.Pattern);
    }

     

    我们能利用PatternChanged事件来监听控件上当前输入数据的改变。

    有趣的地方:

        利用MVVM模式能创建一个任何实体的视图模型,并将其绑定到具有突显属性的数据源上。通过使用样式,这突显的部分将显示在下拉框中。

    说明:

        代码很简单,很容易看懂。有任何问题请提出来改正,谢谢!红色部分是自己加的。

     原文链接:http://www.codeproject.com/KB/WPF/WPF_Autocomplete.aspx


    原文链接: http://www.cnblogs.com/zhuqil/archive/2009/12/15/1625048.html

    你可能感兴趣的:(WPF自动完成控件)