Creating a CustomFilter on the Silverlight 3 AutoCompleteBox

Silverlight 3 has the AutoCompleteBox control which is a textbox that shows suggestions in a drop-down, when the user types text into it. Here’s a very simple example of this control in action.

Just drop in a TextBlock and the Silverlight3 AutoCompleteBox control inside a Canvas as shown below:

 <Canvas x:Name="LayoutRoot" Height="300" Width="300"
TextBlock Text="Enter Country starting with 'A'"
Canvas.Top="5" Canvas.Left="10"/>
input:AutoCompleteBox x:Name="locAuto" Width="200"
Canvas.Top="25" Canvas.Left="10">

Type the following code in the code behind file

public MainPage()
// Assuming this list comes from a service
List<string> cList = new List<string>();
cList.Add("American Samoa");
locAuto.ItemsSource = cList;

Now run the application and on typing ‘A’, a list of suggestions appear in a drop-down fashion. Observe that there are 7 suggestions given to the user.

Silverlight AutoCompleteBox

We will now apply a custom filter to this AutoCompleteBox and filter out those countries whose length is not greater than 5. To do so, create a method that accepts two parameters: the user text and the text that has to be matched

public bool AutoFilter(string text, string item)
return (item.Length > 5);

The final step is to set the ItemFilter property of the AutoCompleteBox to a delegate that points to our Filter method

locAuto.TextFilter = AutoFilter;

Run the application again and you will find that ‘Aruba’ is not shown as a suggestion since it’s length is not greater than 5

Silverlight AutoCompleteBox

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: