What is the best way to implement an auto-suggest feature for a textbox in WPF? I have found various article that are convoluted (and old) and some also suggest that there is a control available for this (but its not in my current WPF toolkit). What's the latest/best method for implementing auto-suggest as a user is typing in to a textbox?
A good product requires good user interaction. Products that are using search boxes will be expected to have auto-completion/suggestion feature. In WPF platform, the default text box control does not have any built-in auto-completion/suggestion feature.
To start, please create a C# WPF project. From the Toolbox panel, drag a TextBox control to the designer window. Now, in the XAML markup, changed the Text attribute to be an empty string. Tip: The Text property indicates the string displayed (or typed by the user) into the TextBox. Also, add a TextChanged attribute.
The TextBox control provides support for basic text input in WPF applications. Gets or sets the style used by this element when it is rendered. Represents a control that provides a scroll bar that has a sliding Thumb whose position corresponds to a value.
To start, please create a C# WPF project. From the Toolbox panel, drag a TextBox control to the designer window. Now, in the XAML markup, changed the Text attribute to be an empty string. Tip: The Text property indicates the string displayed (or typed by the user) into the TextBox.
First approach is to use ComboBox because it already have such functionality. You can use TextSearch feature of it. To enable this feature use this code (sorry, it is quick and dirty):
<ComboBox ItemsSource="{Binding AutoSuggestionVariants}">
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="TextSearch.Text" Value="{Binding}" />
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
Also if you need it, you can restyle combo box such that it will look like a text box (remove button and popup list).
Another approach is to use CollectionView. This article describes how to do about the same feature as TextSearch for combo box. I think you can adopt this idea to text box.
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With