In this article I will talk about the way to create searchable list box. The list box will filter the data as you type in the textbox.
Let's write code to implement it.
Step 1: Create a silverlight for Windows Phone project.
Step 2: Open MainPage.xaml and put below code inside Grid to create a textbox and a listbox. The textbox has TextChanged event.
< TextBox x:Name="txtSearch" TextChanged="txtSearch_TextChanged" Text="" Margin="0,-500,0,0" Height="80" ></TextBox> <ListBox x:Name="listBox" FontSize="26" Height="580" Margin="0,100,0,0"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding coffeeNames}" Width="300" Margin="10,15,0,0" Height="55"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
Step 3: Now create a class Coffee which will be used to bind the data to listbox.
public class Coffee { public string coffeeNames { get; set; } }
Step 4: Now create a class level variable lstCoffees like below in MainPage.xaml.cs.
public partial class MainPage : PhoneApplicationPage { List<Coffee> lstCoffees = null;
Step 5: Add OnNavigatedTo method in MainPage.xaml.cs like below to create the list and bind to listbox.
protected override void OnNavigatedTo(NavigationEventArgs args) { lstCoffees = new List<Coffee>(); lstCoffees.Add(new Coffee() { coffeeNames = "Coffee Tables" }); lstCoffees.Add(new Coffee() { coffeeNames = "Coffee Machines"}); lstCoffees.Add(new Coffee() { coffeeNames = "Coffee Cakes"}); lstCoffees.Add(new Coffee() { coffeeNames = "Coffee Toffee"}); lstCoffees.Add(new Coffee() { coffeeNames = "Coffee Sweet"}); this.listBox.ItemsSource = lstCoffees; }
Step 6: Place textchanged method in MainPage.xaml.cs which will trigger as an when the text get changed in the textbox and bind the filtered data to listbox.
private void txtSearch_TextChanged(object sender, TextChangedEventArgs e) { if (lstCoffees != null) { this.listBox.ItemsSource = lstCoffees.Where(w => w.coffeeNames.ToUpper().Contains(txtSearch.Text.ToUpper())); } }
Step 7: Now run the application you will get the list like below.
Step 8: Now type T in the textbox and the result will be filtered like below.

This ends the article of searchable list box in Windows Phone.
|