February 19, 2010

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"
HorizontalAlignment="Left">
<
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">
</
input:AutoCompleteBox>
</
Canvas>

Type the following code in the code behind file

public MainPage()
{
InitializeComponent();
// Assuming this list comes from a service
List<string> cList = new List<string>();
cList.Add("Afghanistan");
cList.Add("Albania");
cList.Add("Algeria");
cList.Add("American Samoa");
cList.Add("Andorra");
cList.Add("Angola");
cList.Add("Aruba");
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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Creating a CustomFilter on the Silverlight 3 AutoCompleteBox"
 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions