Listbox Control in WPF

Introduction

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!

image1.gif

Here, we will see a basic example first.

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

image2.gif

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

image3.gif

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.

image4.gif

Now, we have the similar window:

image5.gif

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>
</ListBox>

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.

image6.gif

In your Design Window you are supposed to get this:

image7.gif

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.

image8.gif

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.

image9.gif

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.