Take the 2-minute tour ×

I understand that if one has a listBox one can easily add items to it doing something like this:

ListBox myList = new ListBox();
myList.Items.Add("Added Item 1");
myList.Items.Add("Added Item 2");
myList.Items.Add("Added Item 3");

I initially do not know how many items will be added to the list so I don't add static content like I do here, I iterate through a for loop and add items that way. Moving on...

How can I not just add items to the listbox, but also make each one clickable. For Example say have an array of 12 GUIDs, and for each guid Item I add to the listBox .i.e.


And then react differently depending on what guid was selected?

And another thing, how does one style listBox Items? Other than them just showing up as boring strings stacked under each other?

Thanks in advance!

share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

Suppose you have a collection of GUIDs.

var guids = new List<Guid>();

You can then bind this collection to your ListBox control.

myList.ItemsSource = guids;

The ListBox control will automatically update depending on the contents of your guids collection.

To handle the click event for an item in the ListBox, you need to handle the control's SelectionChanged event.

Hook up the event handler.

<ListBox Name="MyList" 

Now you can write the necessary code in the event handler:

private void MyList_SelectionChanged(object sender, 
    System.Windows.Controls.SelectionChangedEventArgs e)
    // Find out which item was clicked
    if (e.AddedItems.Count > 0)
        var myGuid = e.AddedItems[0] as Guid;
        if (myGuid == null)
        // ...

To style each item in the ListBox. Well that's a whole other question. Start with binding your ListBox to your datasource (GUID collection in this case).

Then in XAML you can freely design the contents of the ListBox. Use the ItemTemplate and DateTemplate of the ListBox. In the template you can specify what the ListBox should render for each item.

Let's render a TextBlock in a 1x1 grid for each item. Just bind the TextBlock's Text property to one of the ListBox item's properties.

<ListBox Name="MyList" 
                   <ColumnDefinition Width="*" />
                   <ColumnDefinition Width="*" />

                   <RowDefinition Height="*" />

               <TextBlock Grid.Column="1" Text="{Binding ...}" />
share|improve this answer
Crystal clear and right to the point answer. Thank you very much! –  Relborg Jun 25 '12 at 11:41
Just one last question, here in the XAML where you have the Column Definitions. One should be Width and the other Height right? I see both is Width in this case, maybe just a typo yes? Plus, I see RowDefinition doesn't have a Width property. Does it take on it's parents width? And when one defines width and height properties, do you use px, % or what exactly? –  Relborg Jul 9 '12 at 9:20
add comment

Your Answer


