Saturday, September 3, 2011

WPF Combobox with auto-complete/auto-filter


You know these nice ajax/javascript textboxes where you start typing somes text and the website looks up the data in the database and returns a list of items starting with the text.

There is no default control for this in WPF as well. So, time to build one.



View [XAML] contain the following info/code:
     
    <ComboBox x:Name="cmName"  
                            ItemsPanel="{DynamicResource ItemsTemplate}"  
                            Padding="4 3"  
                            Width="170"  
                            IsEditable="True"  
                            IsTextSearchEnabled="False"  
                            Text="{Binding TextBinding}"  
                            IsDropDownOpen="{Binding IsDropDownOpen}"  
                            ItemsSource="{Binding SourceBinding}"  
                            DisplayMemberPath="Name"  
                            SelectedValue="{Binding Path=SelectedEmailThreadingFrom}"  
                            Grid.ColumnSpan="2"  
                            Margin="43,2,-8,-24"  
                            Grid.Row="6" 
                            />  
                            
View Model [CS] contain the following info/code:
 
      private List<ReturnType> _SourceBinding;

      public List<ReturnType> SourceBinding
      {
        get
        {
            return _SourceBinding;
        }
        set
        {
            _SourceBinding = value;
            RaisePropertyChanged("SourceBinding");
        }
     }

     private string _TextBinding; 
      
     public string TextBinding  
     {  
       get { return _TextBinding; }  
       set  
       {  
         _TextBinding = value;  
         Filter(value);  
         RaisePropertyChanged("TextBinding");  
       }  
     }  

     private bool _IsDropDownOpen;  

     public bool IsDropDownOpen  
     {  
       get { return _IsDropDownOpen; }  
       set  
       {  
         _IsDropDownOpen = value;  
         RaisePropertyChanged("IsDropDownOpen");  
       }  
     }  


Filter Method of View Model [CS] Page
 
     private void Filter(string value)  
     {  
       SourceBinding = (from m in OtherFillList  
                    where m.Name.ToLower().StartsWith(value.ToLower())  
                    select m).ToList();  
       if (SourceBinding != null && SourceBinding.Count > 0)  
       {  
         IsDropDownOpen = true;  
       }  
     }  

0 comments:

Post a Comment