Jumat, 06 September 2013

How to Bind ListBox with XAML Grid Resource: WPF

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.
<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>

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();
MessageBox.Show(selectedValue);
}

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

Tidak ada komentar:

Posting Komentar