How to Bind ListBox with XAML Grid Resource: WPF

September 06, 2013 , , , , 0 Comments

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.
<x:ArrayExtension Type="{ x:Type sys:String}" x:Key="cmbPlacesSource">

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}">

This will show the above items in this listbox as shown in following diagram.

Listbox binding with grid resource: wpf

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.

Listbox binding with grid resource plus scrolling: WPF

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();

It will show a message, containing the selected item, each time when the selection changed of the listbox control.
Select an Item in listbox binding WPF

Subhash Sharma

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google