Listbox Control in WPF


WPF has a wide range of controls in its toolbox, but Listbox is one of the important controls in WPF so far. They are easy to handle in both cases, whether you are assigning a value or binding the value.

In Windows Forms, there are few gestures of the ListBox Control, but in WPF you have your own customs and rules. You can mold it in any way. That's what WPF is!


Here, we will see a basic example first.

Step 1 : Drag a ListBox Control onto your working window and resize it as needed.


Step 2 : In the XAML Window, the IDE has generated the code for you, as in the following:


Now, remove the "Closing Tag" (the forward slash) from the generated code and add </ListBox> to the next line. We will be adding our Values/ListBoxItems within that block.


Now, we have the similar window:


Step 3 : We will now add a few items to ListBox1.

In this format we have the ListBox structure.

<ListBox Height="218"..>
<ListBoxItem>[ITEM 1]</ListBoxItem>
<ListBoxItem>[Item 2] Phone</ListBoxItem>
<ListBoxItem>[Item N]</ListBoxItem>

From the code above we have, "ListBoxItem Tags are enclosed within the ListBox tag", always.

Note: That's the reason why we have removed that SELF CLOSED tag from the ListBox.

And, by default, every control has that Self-Closed Tag.

Step 4 : Add the following Yellow Code to your XAML window.


In your Design Window you are supposed to get this:


Step 5 : We have already populated the listBox.

Next, we will code the "ListBoxItem Selection" and this can be done by programming the "Selection Event".

So, double-click on any ListBoxItem (it would be Android, Window Phone 8… anything).

Note: By doing this, the IDE will generate the Selection Event for that List Box.


Now, put whatever you want in it. I prefer the Message Box.

In that code, I have ed a single argument as a String (in other words ListBox1.SelectedItem.ToString()) that will return the Selected value.

Here, ListBox1 is the name of the ListBox that you can see in the XAML/Properties/Status Bar.


From here, we will go for a Dynamic ListBox, where we will bind the value, in other words Data Binding, in the List Box and customize the List Box with images and fonts.

Up Next
    Ebook Download
    View all
    View all