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


Popular posts from this blog

difference between structure and union in C Language

Difference between Linear search and Binary Search in c language

Difference between static and dynamic websites