-->

Friday, September 6, 2013

Display List of Items using ListBox Control: WPF

Display List of Items using ListBox Control: WPF

ListBox control is used to represent a list of items and select a single or some of the items from these. Most often when we have to opt user to select an item from the list of items, then listbox is used.

In WPF this control is somewhat different from the list box of windows forms. It have some properties to be used most often in programming.
  • DataContext: used to specify the source having list of data, through which it will bind. It may be a binding source or an IList.
  • DisplayMemberPath: indicates the name of an object contained in datasource. Specifies what object will be shown to the user.
  • SelectedValue: get or set the selected value from the list of items.
  • SelectedValuePath: used to specify the selected value from the binding source.
  • SelectedIndex: get or set the index of selected value.
  • SelectedItem: indicates the item which is selected.
The following XAML code will create a listbox with three items and none of them is selected.
<ListBox >
<ListBoxItem>first Item</ListBoxItem>
<ListBoxItem>second Item</ListBoxItem>
<ListBoxItem>third Item</ListBoxItem>
</ListBox>

To select an item, set IsSelected property to true. The above XAML code will show a listbox having three items as shown in following image:

ListBox control introduction WPF

The same listbox can also be generated using the following line of code:
<ListBox >
<ListBoxItem>first Item</ListBoxItem>
<ListBoxItem>second Item</ListBoxItem>
<ListBoxItem>third Item</ListBoxItem>
</ListBox>

The listbox can also formatted using its properties like background, foreground and etc. That is how we created a listbox from XAML code.

Read other related articles

Also read other articles

© Copyright 2013 Computer Programming | All Right Reserved