Blog Views


Thursday, October 13, 2011

Silverlight AutoComplete box (The real deal!!)

Silverlight Introduction

So I have spent quite a bit of time with Silverlight and one thing I really like about it is that if you don't come from a lot of .NET experience, you get a taste of every aspect of the framework. You may not be able to do "everything" WPF or Windows Forms can do, but you get a lot of experience in it all. Th reason for this is although Silverlight is rich and a great patform, it is client side only. NO SERVER END. Web Services are used as the way to communicate with either the web project or any other tool outside of Silverlight (database for example)


Purpose for the Autocomplete boxes??

In my articles I like to explain somewhere a real world explaination of what a particular tool would be used for. In this case, the Autocomplete tool is most often used in two scenarios

The first use case is when your application has a fixed set of things you wish to have the user choose from and don't wish to use a dropdown either because you have too many options for a user to sift through or your users really like the keyboard and want to utilize it to be more efficient. Using AutoComplete boxes allows you to do just that by popping up data values based on what you type in the box (such as looking up someones name).

The second use case for using a AutoComplete box (remember I'm sure there are tons more, these are just 2 common ones) is for search engines. Notice how Google has had for a long time now, the ability to autocomplete your question before you finish? In it's simplest form, this is an autocomplete box that uses a list of words and phrases to match what you are typing on the fly. This is possible using AJAX web methods.

AJAX ( Asynchronous JavaScript and XML)

There is a very special group of web methods called AJAX which allow for a better user experience by making asynchronous calls to the server and instead of the browser waiting for a response from the server before allowing the user to continue interacting with it, the browser continues on it's merry way with the user until it gets a returned CallBack from the Event that was origionally created. I will go into AJAX more in future blogs, but it has definetly matured quite a but since the late 90's.


No more Background.. Lets get the show on the Road

So now that you have some background in what AutoComplete boxes are, what AJAX is, what limits Silverlight etc... Lets get coding. So first lets create a simple person class in the Silverlight Application. If you want to seperate concerns, you can easily do this by placing it in an Entities folder. The Person class should look similar to this:

 public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Department { get; set; }

        public override string ToString()
        {
            return FirstName;
        }
    }

}


Overriding the ToString method allows you to instead of getting the object type, get the First name popup in the autocomplete control

Now lets build ourselves a little repository database (really just a list)

 public class PersonRepository
    {
        Person _person = new Person();
        

        #region DUMMY DATABASE

        public List<Person> GetPersonList()
        {
            List<Person> personList = new List<Person>();

            personList.Add(new Person
            {
                FirstName = "Joe",
                LastName = "Shmo",
                Department = "IT"
            });

            personList.Add(new Person
            {
                FirstName = "Gregg",
                LastName = "Tyler",
                Department = "Software Engineer"
            });

            personList.Add(new Person
            {
                FirstName = "Gary",
                LastName = "Style",
                Department = "Accounting"
            });

            personList.Add(new Person
            {
                FirstName = "Geoff",
                LastName = "Style",
                Department = "Accounting"
            });


            personList.Add(new Person
            {
                FirstName = "Michael",
                LastName = "Style",
                Department = "Accounting"
            });

            personList.Add(new Person
            {
                FirstName = "Matthew",
                LastName = "Style",
                Department = "Accounting"
            });

            personList.Add(new Person
            {
                FirstName = "Mark",
                LastName = "Style",
                Department = "Accounting"
            });


            personList.Add(new Person
            {
                FirstName = "Rebeccca",
                LastName = "Smith",
                Department = "Human Resources"
            });

            personList.Add(new Person
            {
                FirstName = "Richard",
                LastName = "Style",
                Department = "Accounting"
            });

            personList.Add(new Person
            {
                FirstName = "Robert",
                LastName = "Style",
                Department = "Accounting"
            });

            return personList;
        }


        #endregion
    }

Now lets go into the MainPage.xaml file and add a AutoComplete Box from the ToolBox. This will add the proper references and should create a sdk tag type via this line of code at the top of the screen under the UserControl tag sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk". The below code does several things, first, I create two Stack Panels that enacpsulate the AutoComplete box as well as the textbox that will populate with the selected Item.

 <StackPanel Background="LightGray">

            <StackPanel x:Name="AutoRoot"  Orientation="Horizontal">

                <sdk:AutoCompleteBox  x:Name="AutoBox" Width="200">
                    <sdk:AutoCompleteBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <TextBlock Text="{Binding Path=FirstName}"/>
                            </StackPanel>

                        </DataTemplate>
                    </sdk:AutoCompleteBox.ItemTemplate>
                </sdk:AutoCompleteBox>
               </StackPanel>
        </StackPanel>


You will notice that the TextBlock that corresponds to the AutocompleteBox has it's Text property being bound to the FirstName of the Person object. This is important because we are going to do outr autocompltion based on first name. This is all encapsulated in what is known as a Datatemplate.

The final part is the code behind for the MainPage.

 public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            // Create repository and get DB list
            PersonRepository personRepository = new PersonRepository();
            List personList = personRepository.GetPersonList();

            // Bind list to AutoComplete box
            this.AutoBox.ItemsSource = personList;

            #region Set Filters for Autocomplete Direct Reports

            this.AutoBox.ItemFilter = ((search, item) =>
            {

                Person person = item as Person;

                if (personList.Count() != 0)
                {
                    string filter = search;
                    return (person.FirstName.Contains(filter));
                }
                return false;
            });

        }
            #endregion

    }

The first part acesses the repository and gets the list from our database and binds it to the AutoComplete controls ItemSourcw. Then using the AutoCompletes ItemFilter property and lambda expression, You are able to filter inside the list by using the Contains property in the string object as shown below.

return (person.FirstName.Contains(filter));

Hope everyone enjoyed this tutorial. There have been very few tutorials on this and i thought it was important to get this out there.

References

  • http://en.wikipedia.org/wiki/AJAX

No comments:

Post a Comment