More on populating a ListBox using databinding

So, you've created your ObservableCollection array, and set it to your ListView or ListBox as an ItemSource, and it works: when you add an entry to the array, the List control redraws itself. Life is good.

It does seem rather limiting though, that you need to create an array that's a 1D list of items. Like this I mean:

Hmm. Only having one piece of information to associated with each line in the List control is a little.. boring. Am I right?

Could there be a way to create an array of objects, in which each object has, say, a string for including in the menu plus something else? It turns out there is: it turns out the XAML markup can really get rather more involved in your C# than you might expect, compared to, say, Objective C.

As an example, let's create some data that stores a name for a menu item and another piece of information to store a URL - as if we were writing a bookmark feature for a web browser. Rather than use a ListView, I'm using a ListBox. The two controls are very similar, but the ListView has an extra view associated with it and defaults to extended selection. In a nutshell: in a simple menu, ListBox is better.

The structure to store the data might look like this:

In the WebLink class, we define an object that can store a Name and a URL as strings, and we ask for the getters and setters to allow us to read and write to them. We then wrap this up inside the LinkCategory class, which creates the ObservableCollection we need for the data-binding to work.

We can then set some initial values, like this:

 We then need to do two more things. The first is to assign the list of links as a source for the XAML ListBox, which we do like this:

And secondly, we need some cool code that will data-bind on the specific field in our data array. That code looks like this:

 You can see that we are actually opening up the ListBox's internal template and creating a single TextBlock, which is then data-bound to that Name value - and Name is taken from your C# source code. Neat, huh?

As we are using a standard TextBlock to display the name, you are of course free to change the colors and text styles to suit your app. And as we are putting that TextBlock inside a standard StackPanel, you can also add more TextBlocks, or even some images. Or buttons. Or any other XAML control that would seem like a good idea to put into a list.

The final piece in the puzzle is this: how do we get access to the URL that is associated with the menu item the user has just clicked? Here is the click-handler code that should make this clear. This code assumes we have a WebView control ready to load up the URL.

All we need to do is make use of the sender object that is passed into our handler, and check the SelectedIndex property. That gives us a value which can be used as an index, to retrieve the URL from our array.

Now we can create our bookmark app, like this: