In the previous article, we have learnt about the listbox and some of the properties of listbox. Resources provide a way to reuse the objects and values by other controllers in the code. As we created a grid resource in the combobox binding, that resource can be used here easily.
Just review the grid resource written as below, where type indicates the type of values defined in it, and the key name will be used to bind other control through it.
Now add a listbox and use its itemsSource property. This property is used to get or set a collection used to generate the content of itemscontrol.
This will show the above items in this listbox as shown in following diagram.
As the items increases or height decreases, this control will use scroller to view the extra items. Let me set height of above listbox to 30 and lookout the output.
We can get the selected item’s value from the selection changed event of this control. Write the following code in selection Changed event of listbox
It will show a message, containing the selected item, each time when the selection changed of the listbox control.
Just review the grid resource written as below, where type indicates the type of values defined in it, and the key name will be used to bind other control through it.
<Grid.Resources>
<x:ArrayExtension Type="{ x:Type sys:String}" x:Key="cmbPlacesSource">
<sys:String>London</sys:String>
<sys:String>Italy</sys:String>
<sys:String>California</sys:String>
<sys:String>France</sys:String>
</x:ArrayExtension>
</Grid.Resources>
<x:ArrayExtension Type="{ x:Type sys:String}" x:Key="cmbPlacesSource">
<sys:String>London</sys:String>
<sys:String>Italy</sys:String>
<sys:String>California</sys:String>
<sys:String>France</sys:String>
</x:ArrayExtension>
</Grid.Resources>
Now add a listbox and use its itemsSource property. This property is used to get or set a collection used to generate the content of itemscontrol.
<ListBox Name=”listBox” Width="200"
ItemsSource="{StaticResource cmbPlacesSource}">
</ListBox>
ItemsSource="{StaticResource cmbPlacesSource}">
</ListBox>
This will show the above items in this listbox as shown in following diagram.
As the items increases or height decreases, this control will use scroller to view the extra items. Let me set height of above listbox to 30 and lookout the output.
We can get the selected item’s value from the selection changed event of this control. Write the following code in selection Changed event of listbox
private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string selectedValue = listBox.SelectedItem.ToString();
MessageBox.Show(selectedValue);
}
{
string selectedValue = listBox.SelectedItem.ToString();
MessageBox.Show(selectedValue);
}
It will show a message, containing the selected item, each time when the selection changed of the listbox control.