Introduction
In this article we will explore what are features available for a ListBox in Silverlight 3 Application.
Crating Silverlight Project
Fire up Visual Studio 2008 and create a Silverlight Application. Name it as ListBoxInSL3.
Here is the basic idea what we are going to do in this Silverlight Application: We will add ListBox and a TextBlock, whatever item you select from the ListBox it will be displayed in the TextBox.
Open Expression Blend 3 and start designing the application. Follow the below figure to have better idea.
If you look at the Objects and Timeline Pane you will find these following controls are added with specific names.
In ListBox we are going to explore the property called SelectionMode. If you want to see it, just select ListView and in the Properties Pane in Common Properties you will find it.
Selection Mode has three modes:
Now open the solution in Visual Studio 2008, we have code to write. J
We will use the Multiple Selection Mode for the ListBox.
<ListBox x:Name="MyListBox" Height="100" SelectionMode="Multiple" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Margin="8,39,0,0"/>
Add a List of strings as the Item Source of the ListBox.
List<string> myList = new List<string> { "C", "C++", "C#", "Java", "Visual Basic", "XAML" };
public MainPage()
{
InitializeComponent();
MyListBox.ItemsSource = myList;
}
Now we will add an event to the ListBox, called SelectionChanged.
<ListBox x:Name="MyListBox" Height="100" SelectionMode="Multiple" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Margin="8,39,0,0" SelectionChanged="MyListBox_SelectionChanged"/>
Now in MainPage.xaml.cs find the event handler method and add the following code, to make sure what are the selections we have made.
private void MyListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedExp = MyListBox.SelectedItems;
Experience.Text = string.Empty;
foreach (string langName in selectedExp)
{
if (Experience.Text.Length>0)
{
Experience.Text += ", ";
}
Experience.Text += langName;
}
}
Now Run your application and select multiple values from the ListBox and you will find the selections are added to the TextBlock.
Single Mode
Now you might have thought of using the other two Modes: Single and Extended.
Single, as the name says you will be able to select only a single item in the ListBox.
What is Extended Mode?
It's nothing but the combination of both Single Mode and Multiple Mode. If you normally select it will be Single select mode and if you Press CTRL and select it will be Multiple mode.
Go ahead and try for it.
Enjoy Coding.