WPF AutoComplete Folder TextBox

Introduction

This article demonstrates how to create a TextBox in WPF that can suggest items at runtime based on an input, in this case, disk drive folders.

Background

There is a number of AutoComplete TextBox implementation around but some don't support data binding, others don't support runtime items polling and so on. After lot of research and Googling, I decided to write my own instead of continue looking for one.

My Design process

My first design is based on ComboBox, I copy the default template and remove the drop down button and develop from that, it doesnt work because combobox have it's own autocomplete mechanism which will change the selection of textbox when Items is changed, it's not designed for Items that change at realtime.

So the second design is based on TextBox, I create the following style,
  1. <Style x:Key="autoCompleteTextBox" TargetType="{x:Type TextBox}">  
  2.    <Setter Property="Template">  
  3.       <Setter.Value>  
  4.          <ControlTemplate TargetType="{x:Type TextBoxBase}">  
  5.             <Grid x:Name="root">  
  6.                <ScrollViewer Margin="0" x:Name="PART_ContentHost"/>  
  7.                   <Popup x:Name="PART_Popup" AllowsTransparency="true"  
  8.                      Placement="Bottom" IsOpen="False"  
  9.                         PopupAnimation="{DynamicResource  
  10.                         {x:Static SystemParameters.ComboBoxPopupAnimationKey}}">  
  11.                            <ListBox x:Name="PART_ItemList" SnapsToDevicePixels  
  12.                               ="{TemplateBinding  
  13.                               SnapsToDevicePixels}"  
  14.                           VerticalContentAlignment="Stretch" HorizontalContentAlignment  
  15.                        ="Stretch"  
  16.                     KeyboardNavigation.DirectionalNavigation="Contained" />  
  17.                </Popup>  
  18.            </Grid>  
  19.          </ControlTemplate>  
  20.       </Setter.Value>  
  21.    </Setter>  
  22. </Style>  
And then create a custom control and hook the style to it,
  1. <TextBox x:Class="QuickZip.Controls.SelectFolderTextBox" Style="{DynamicResource  
  2.    autoCompleteTextBox}" >...  
  3. </TextBox>  
PART_ContentHost is actually a control that TextBoxView, it is required for TextBox template (with that name), or the control won't function, the another two part (PART_Popup and PART_ItemList) is defined so I can use them in the custom control,
  1. public partial class SelectFolderTextBox: TextBox {  
  2.     Popup Popup {  
  3.         get {  
  4.             return this.Template.FindName("PART_Popup"this) as Popup;  
  5.         }  
  6.     }  
  7.     ListBox ItemList {  
  8.         get {  
  9.             return this.Template.FindName("PART_ItemList"this) as ListBox;  
  10.         }  
  11.     }  
  12.     ScrollViewer Host {  
  13.         get {  
  14.             return this.Template.FindName("PART_ContentHost"this) as ScrollViewer;  
  15.         }  
  16.     }  
  17.     UIElement TextBoxView {  
  18.         get {  
  19.             foreach(object o in LogicalTreeHelper.GetChildren(Host)) return o as UIElement;  
  20.             return null;  
  21.         }  
  22.     }  
  23. }  
The output looks like the following Figure.

WPF AutoComplete Folder TextBox

If text is changed, the suggestion item list is updated as well,
  1. protected override void OnTextChanged(TextChangedEventArgs e) {  
  2.     if (_loaded) {  
  3.         try {  
  4.             if (lastPath != Path.GetDirectoryName(this.Text)) {  
  5.                 lastPath = Path.GetDirectoryName(this.Text);  
  6.                 string[] paths = Lookup(this.Text);  
  7.                 ItemList.Items.Clear();  
  8.                 foreach(string path in paths)  
  9.                 if (!(String.Equals(path, this.Text, StringComparison.CurrentCultureIgnoreCase))) ItemList.Items.Add(path);  
  10.             }  
  11.             Popup.IsOpen = true;  
  12.             //I added a Filter so Directory polling is only called once per directory, thus improve speed  
  13.             ItemList.Items.Filter = p => {  
  14.                 string path = p as string;  
  15.                 return path.StartsWith(this.Text, StringComparison.CurrentCultureIgnoreCase) && !(String.Equals(path, this.Text, StringComparison.CurrentCultureIgnoreCase));  
  16.             };  
  17.         } catch {}  
  18.     }  
  19. }  
A number of handlers is then defined,
  1. public override void OnApplyTemplate() {  
  2.     base.OnApplyTemplate();  
  3.     _loaded = true;  
  4.     this.KeyDown += new KeyEventHandler(AutoCompleteTextBox_KeyDown);  
  5.     this.PreviewKeyDown += new KeyEventHandler(AutoCompleteTextBox_PreviewKeyDown);  
  6.     ItemList.PreviewMouseDown += new MouseButtonEventHandler(ItemList_PreviewMouseDown);  
  7.     ItemList.KeyDown += new KeyEventHandler(ItemList_KeyDown);  
  8. }  
AutoCompleteTextBox_PreviewKeyDown

if user press down button, the textbox will move focus to the Listbox, so the user can choose an item from it, this is placed in PreviewKeyDown instead of KeyDown because TextBox's mechanism will consume the event before it reach KeyDown if the button is down button.
  1. void AutoCompleteTextBox_PreviewKeyDown(object sender, KeyEventArgs e) {  
  2.     if (e.Key == Key.Down && ItemList.Items.Count > 0 && !(e.OriginalSource is ListBoxItem)) {  
  3.         ItemList.Focus();  
  4.         ItemList.SelectedIndex = 0;  
  5.         ListBoxItem lbi = ItemList.ItemContainerGenerator.ContainerFromIndex(ItemList.SelectedIndex) as ListBoxItem;  
  6.         lbi.Focus();  
  7.         e.Handled = true;  
  8.     }  
  9. }  
AutoCompleteTextBox_KeyDown

if user press <enter> button, the textbox will close the popup and update the binding.
  1. void AutoCompleteTextBox_KeyDown(object sender, KeyEventArgs e) {  
  2.     if (e.Key == Key.Enter) {  
  3.         Popup.IsOpen = false;  
  4.         updateSource();  
  5.     }  
  6. }  
ItemList_PreviewMouseDown and ItemList_PreviewMouseDown

if user press <enter> button (or select by mouse), the text textbox will be updated with ListBox.SelectedValue, and then update the binding.
  1. void ItemList_KeyDown(object sender, KeyEventArgs e) {  
  2.     if (e.OriginalSource is ListBoxItem) {  
  3.         ListBoxItem tb = e.OriginalSource as ListBoxItem;  
  4.         Text = (tb.Content as string);  
  5.         if (e.Key == Key.Enter) {  
  6.             Popup.IsOpen = false;  
  7.             updateSource();  
  8.         }  
  9.     }  
  10. }  
  11. void ItemList_PreviewMouseDown(object sender, MouseButtonEventArgs e) {  
  12.         if (e.LeftButton == MouseButtonState.Pressed) {  
  13.             {  
  14.                 TextBlock tb = e.OriginalSource as TextBlock;  
  15.                 if (tb != null) {  
  16.                     Text = tb.Text;  
  17.                     updateSource();  
  18.                     Popup.IsOpen = false;  
  19.                     e.Handled = true;  
  20.                 }  
  21.             }  
  22.         }  
updateSource is required because I bound text's UpdateSourceTrigger as Explicit, if updateSource is not called it wont update the text,
  1. void updateSource()   
  2. {  
  3.     if (this.GetBindingExpression(TextBox.TextProperty) != nullthis.GetBindingExpression(TextBox.TextProperty).UpdateSource();  
  4. }  
The component is working now, but if you want to add validation as well, read below,

To support validation, a Validation Rule is written,

If the path is not found or an exception raised when looking up, it will return ValidationResult false, the error will be accessed by using the attached properties Validation.Errors and Validation.HasError.
  1. public class DirectoryExistsRule: ValidationRule {  
  2.     public static DirectoryExistsRule Instance = new DirectoryExistsRule();  
  3.     public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {  
  4.         try {  
  5.             if (!(value is string)) return new ValidationResult(false"InvalidPath");  
  6.             if (!Directory.Exists((string) value)) return new ValidationResult(false"Path Not Found");  
  7.         } catch (Exception ex) {  
  8.             return new ValidationResult(false"Invalid Path");  
  9.         }  
  10.         return new ValidationResult(truenull);  
  11.     }  
  12. }  
and change the binding : (to use the created Validation rule, noted that UpdateSourceTrigger is Explicit. )
  1. <local:SelectFolderTextBox x:Name="stb" DockPanel.Dock="Bottom" Margin="4,0,0,0">  
  2.     <local:SelectFolderTextBox.Text>  
  3.         <Binding Path="Text" UpdateSourceTrigger="Explicit">  
  4.             <Binding.ValidationRules>  
  5.                 <t:DirectoryExistsRule />  
  6.             </Binding.ValidationRules>  
  7.         </Binding>  
  8.     </local:SelectFolderTextBox.Text>  
  9. </local:SelectFolderTextBox>  
Now the textbox show a red border if directory not exists. As a red border isnt clear enough, we can change the behavior :
to disable the default red border,
  1. <Style x:Key="autoCompleteTextBox" TargetType="{x:Type TextBox}">  
  2.     <...>  
  3.   <Setter Property="Validation.ErrorTemplate">  
  4.         <Setter.Value>  
  5.             <ControlTemplate>  
  6.                 <AdornedElementPlaceholder />  
  7.                 < !-- The TextBox Element -->  
  8.             </ControlTemplate>  
  9.         </Setter.Value>  
  10.    </Setter>  
  11. </Style>  
then change the control template, which will show the dockWarning when Validation.HasError,
  1. <ControlTemplate TargetType="{x:Type TextBoxBase}">  
  2.     <Border Name="Border" CornerRadius="2" Background="{StaticResource WindowBackgroundBrush}" BorderBrush="{StaticResource SolidBorderBrush}" BorderThickness="1" Padding="1">  
  3.         <Grid x:Name="root">  
  4.             <...>  
  5.                 <DockPanel x:Name="dockWarning" Visibility="Collapsed" LastChildFill="False">  
  6.                     <Border DockPanel.Dock="Right" BorderBrush="Red" Background="Red" BorderThickness="2" CornerRadius="2,2,0,0">  
  7.                         <TextBlock x:Name="txtWarning" DockPanel.Dock="Right" Text="{TemplateBinding ToolTip}" VerticalAlignment="Top" Background="Red" Foreground="White" FontSize="10" />  
  8.                         <Border.RenderTransform>  
  9.                             <TranslateTransform X="2" Y="{Binding ElementName=dockWarning, Path=ActualHeight,  
  10. Converter={x:Static t:InvertSignConverter.Instance}}" />  
  11.                             <!--TranslateTransform move the border to upper right corner, outside the TextBox -->  
  12.                             <!--InvertSignConverter is a IValueConverter that change + to -, - to + -->  
  13.                         </Border.RenderTransform>  
  14.                     </Border>  
  15.                 </DockPanel>  
  16.         </Grid>  
  17.     </Border>  
  18.     <ControlTemplate.Triggers>  
  19.         <MultiTrigger>  
  20.             <MultiTrigger.Conditions>  
  21.                 <Condition Property="Validation.HasError" Value="true" />  
  22.                 <Condition SourceName="PART_Popup" Property="IsOpen" Value="False" />  
  23.             </MultiTrigger.Conditions>  
  24.             <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />  
  25.             <Setter TargetName="dockWarning" Property="Visibility" Value="Visible" />  
  26.             <Setter TargetName="Border" Property="BorderThickness" Value="2" />  
  27.             <Setter TargetName="Border" Property="Padding" Value="0" />  
  28.             <Setter TargetName="Border" Property="BorderBrush" Value="Red" />  
  29.         </MultiTrigger>  
  30.     </ControlTemplate.Triggers>  
  31. </ControlTemplate>  
History
  • 22-12-08 Initial version
  • 25-12-08 - Add Ghost image when picking from ItemList
  • 25-12-08 - Handle PageUp/Down/Up Button in Textbox
  • 25-12-08 - Handle \ / Escape button in ItemList
  • 25-12-08 - Disabled the caching system as it dont work well.
  • 25-12-08 Updated version 1
License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public Licence.