Jumat, 06 September 2013

How to Bind ListBox with List: WPF

According to the previous post we don’t need to define the items first. Means the source having the items to be bind with listbox. In the XAML define a listbox with some common properties you want as height, width and etc. Don’t forget the name property, because it will be used to assign itemsSource for this control.

<ListBox Name="listBox" Width="200"/>

Create a list of type string and add some items with Add() method of list. I have added the same items as in grid resources.
List<string> strList = new List<string>();
strList.Add("London");
strList.Add("Italy");
strList.Add("California");
strList.Add("France");
listBox.ItemsSource = strList;

Just run the code and the same window will be shown with a listbox containing above four items.

Binding of Listbox with C# List: WPF

Listbox have a property selectedIndex which is used to get or set the selected index of the control. To select an item by default we can use this property as:

listBox.SelectedIndex = 2;

Write the above line of code just below the c# code, and California will be selected.

Tidak ada komentar:

Posting Komentar