Thursday, August 26, 2010

Customize AutoCompleteBox in WPF

Introduction

In this article we will see how we can customize an AutoCompleteBox in WPF.

1.gif
 
Creating a WPF Project

Fire up Visual Studio 2010, create a WPF Application, and name it as AutoCompleteSample2.

2.gif

Sometimes we need to display more than one item in the auto complete box suggestion. For example state code with state names.

So we got two columns in the suggestion. 

I was trying hard to customize it in Expression Blend, but turns out it was very simple.

Let's have a class of Codes with the following properties.

3.gif 

Now let's create a list of Codes and bind that to the AutoCompleteBox.

4.gif 

Now without customization, let's run the application and see what we are getting as output.

5.gif 

So we are getting the Class name instead.

Now we can simply customize the Item Template of the AutoCompleteBox as follows:

6.gif 

As you see in the above code display, I have two textboxes which would bind to the respective properties of the ItemsSource.

Now let's run the application again and see the output.

7.gif 

In the above figure, I have typed "a" but still it's displaying all the states.

To achieve that we need to have the property called ValueMemberPath.

Set the value as the property you need to bind, in our case Name.



See full details: http://www.c-sharpcorner.com/UploadFile/dpatra/2375/Default.aspx