Introduction
In this article I'll explain how to create an "auto complete box" control with two line items. An auto complete box is a combination of two controls, one is used for input and that is a text box, the second one is used for selecting the item and that is similar to a list box. In this article I'll cover the "auto complete box" control with two line items. After reading this article you will be familiar with the advanced features of "auto complete box" control and how to use it in your apps or existing projects. let's start with the description of this control.
Auto Complete Box Control
As the name indicates, it's a control that provides an auto text completion capability to the user on the basis of predefined collections. This control is a combination of a text box and a list box. The text box is where the user types the text and the list box works as a container of items that can be selected for completing the text box value. The list box contains the items that are filtered on the basis of input. The two line items basically consist of two text blocks. Both of the text blocks can be used for various purposes. The list box is known as drop down since it opens only when there is an item to select.
Some of the properties of an Auto Complete Box that I have used in this demo are as follows:
- Text
This property is used for setting the default text in the text box of the auto complete box.
- Filter Mode
A very important and useful one. It allows you to set the type of filtering you want on collections. Some of the filters are like contains, contains case sensitive, equal and so on.
- ValueMemberPath
This property is very essential for the proper working of the auto complete box. This property sets the value that is to be used for comparison. The Filter method compares the input with the item assigned to this property.
Apart from the above properties the following two events are also used.
- Selection changed
This event is fired when the item selected in the drop down has changed.
- Got Focus
This event is fired when the text box gets the focus.
I have also used an item template and data template to design the UI of the dropdown items.
Installing Windows Phone 8 Toolkit
Before you can run the following demo you need to install a Windows Phone 8 toolkit in your project. It's very easy to do this.
Use the following procedure to install the Windows Phone 8 toolkit using Nugget:
-
Open your app project (either an existing one or a new one).
-
From the toolbar select "Tools" -> "NuGet Package Manager" -> "Package Manager Console".
-
Now in the Package Manager Console type the following:
Install-Package WPtoolkit
After typing this you will probably see the log similar to this:
install-package wptoolkit
'WPtoolkit 4.2013.08.16' already installed.
Adding 'WPtoolkit 4.2013.08.16' to Demo.
Successfully added 'WPtoolkit 4.2013.08.16' to Demo.
- The next step is to add its reference to the XAML page. To do this just add this line:
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
Demo
The following demo demonstrates the basic code required for adding the auto complete box to any project. The code is very simple to follow and works in the following steps:
- Add the auto complete box control to your design file.
- Provide whatever name you want to the control. This name will be used from the code behind for referring and controlling its behavior.
- Set the value member path equal to "Key" since we are comparing input against the dictionary keys.
- Now create an item template and a data template.
- Add two text blocks to the data template and bind them with dictionary key and value properties.
- Now move to the code behind. In the page constructor we have the "startDemo" function that basically initiates the demo.
- Inside the start demo we have the "createRandomItemSource" function that prepares a collection of randomly generated strings. These strings serve the purpose of auto completion source for the auto completion box control. Here the item source is of dictionary type.
- The Selection change event is used for fetching the selected item.
- The Search text is text being entered by the user in the text box and it is retrieved by the Search text property.
Let's see how to code it.
XAML
- <phone:PhoneApplicationPage
- x:Class="Demo.MainPage"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
- xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
- mc:Ignorable="d"
- FontFamily="{StaticResource PhoneFontFamilyNormal}"
- FontSize="{StaticResource PhoneFontSizeNormal}"
- Foreground="{StaticResource PhoneForegroundBrush}"
- SupportedOrientations="Portrait" Orientation="Portrait"
- shell:SystemTray.IsVisible="True">
-
- <!--LayoutRoot is the root grid where all page content is placed-->
- <Grid x:Name="LayoutRoot" Background="Transparent">
- <Grid.RowDefinitions>
- <RowDefinition Height="112.662"/>
- <RowDefinition Height="655.338"/>
- </Grid.RowDefinitions>
-
- <!--TitlePanel contains the name of the application and page title-->
- <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,512" Grid.RowSpan="2">
- <TextBlock Text="Demo" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
- <TextBlock Text="Demo" Margin="9,-7,0,0" FontSize="40" />
- </StackPanel>
-
- <!--ContentPanel - place additional content here-->
- <StackPanel Orientation="Vertical" Grid.Row="1" Margin="0,0,0,352.338">
-
- <toolkit:AutoCompleteBox Name="acb" Text="Start typing..." FilterMode="Contains" ValueMemberPath="Key" SelectionChanged="acb_SelectionChanged" GotFocus="acb_GotFocus">
- <toolkit:AutoCompleteBox.ItemTemplate>
- <DataTemplate>
- <StackPanel Orientation="Vertical">
- <TextBlock Text="{Binding Path=Key}" FontSize="25" Foreground="Red"></TextBlock>
- <TextBlock Text="{Binding Path=Value}" FontSize="20"></TextBlock>
- </StackPanel>
- </DataTemplate>
- </toolkit:AutoCompleteBox.ItemTemplate>
- </toolkit:AutoCompleteBox>
- </StackPanel>
- <TextBlock Text="Selected Item:" FontSize="25" Margin="0,406,307,209.338" Grid.Row="1"></TextBlock>
- <TextBlock Name="selectedText" TextWrapping="Wrap" Text="None" FontSize="25" Margin="178,406.338,0,178" Grid.Row="1"></TextBlock>
- <TextBlock Text="Searched Text:" FontSize="25" Margin="0,482.338,307,133" Grid.Row="1"/>
- <TextBlock x:Name="searchText" FontSize="25" Text="None" Margin="178,482.338,0,133" Grid.Row="1"/>
- </Grid>
- </phone:PhoneApplicationPage>
C# Code Behind
- using Microsoft.Phone.Controls;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Windows;
- using System.Windows.Controls;
- using System.Diagnostics;
- using Microsoft.Phone.Tasks;
- using System.IO;
-
- namespace Demo
- {
- public partial class MainPage : PhoneApplicationPage
- {
-
- public MainPage()
- {
- InitializeComponent();
- startDemo();
- }
- Dictionary<string, string> textList = new Dictionary<string, string>();
- private void startDemo()
- {
- createRandomItemSource();
- }
- private void createRandomItemSource()
- {
- for (int i = 0; i < 50; i++)
- {
- textList.Add(getRandomText(), getRandomText() + getRandomText() + getRandomText());
- }
- acb.ItemsSource = textList;
- }
- Random random = new Random();
- private string getRandomText()
- {
- var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- var result = new string(
- Enumerable.Repeat(chars, 8)
- .Select(s => s[random.Next(s.Length)])
- .ToArray());
- return result.ToLower();
- }
- private void acb_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- if (acb.SelectedItem != null)
- {
- selectedText.Text = acb.SelectedItem.ToString();
- searchText.Text = acb.SearchText;
- }
- }
-
- private void acb_GotFocus(object sender, RoutedEventArgs e)
- {
- acb.Text = "";
- }
- }
- }
Output