Preface and Thanks

I am a .NET programmer, but a busy one. I do VB.NET and C#, ASP.NET / WinForms / WPF / WCF, Flash, Silverlight, the lot. Basically, I keep my toe in. But when I started writing this article series, I naturally chose my favourite language (which happens to be C#). I since got an email from an individual who requested that I publish this series with source code in VB.NET and C#. I simply stated I didn't have time. So this individual (Robert Ranck) volunteered to help out, and do the translation to VB.NET, based on my original C# projects.

So for that and the subsequent VB.NET projects that you will find here, I ask you to thank Robert Ranck. Cheers Robert, your contributions will surely make this series more open to all .NET developers.

And thanks also go out to Karl Shifflett (A.K.A. the blog/article machine, also known as the Molenator) for answering my dumb VB .NET questions. And I'd also like to mention that Karl has just started a more advanced series of WPF articles (which at present will be in VB.NET, but will hopefully appear in C# as well). Karl's new series is excellent, and I urge you all to encourage Karl on this series. It's not easy obligating oneself to write an entire series in one language, let alone two. Karl's first article is located right here, have a look for yourself. Personally, I love it.

Introduction

This article is the fifth in my series of beginner's articles for WPF. In this article, we will discuss databinding. The proposed schedule for this series will still be roughly as follows:

I will not be covering the following collection based binding areas, so if you want to know more about these, you'll have to do a bit of extra research using the links provided (see I'm 1/2 OK, at least I researched the correct links for you):

Databinding is actually not that new (OK, how it's done in WPF is new), but we have had binding in ASP.NET and WinForms for some time now. WPF has borrowed from both of these to create a really, really good binding framework. But what is this binding stuff, for those of you have never heard of it.

Well, basically, binding allows UI Elements to obtain their data either from other UI Elements or business logic objects/classes. So in theory, it's very simply, we have a source that provides a value, and we have a target that wants to use the source's value, and we kind of glue them together using binding.

A typical binding arrangement is as follows:

Typically, each binding has these four components: a binding target object, a target property, a binding source, and a path to the value in the binding source to use.

The target property must be a Dependency Property (which I've just covered). Most UIElement properties are Dependency Properties, and most Dependency Properties, except read-only ones, support data binding by default.

That's a very simplified version of what's going on in binding.

Of course, to facilitate these binding operations, there are many separate considerations and bits of syntax that need to be considered. In the following sub sections, you will look at some (no, not all, I'd be here all year) of the binding syntax and ideas/approaches to creating happy bindings.

There is one important thing to know before we get into the ins and outs of Databinding, and that is the DataContext property that every FrameworkElement has. DataContext is a concept that allows elements to inherit information from their parent elements about the data source that is used for binding, as well as other characteristics of the binding, such as the path. DataContext can be set directly to a Common Language Runtime (CLR) object, with the bindings evaluating to properties of that object. Alternatively, you can set the data context to a DataSourceProvider object.

This Dependency Property inherits property values. If there are child elements without other values for DataContext established through local values or styles, then the property system will set the value to be the DataContext value of the nearest parent element with this value assigned.

In XAML, DataContext is most typically set as a Binding declaration. You can use either property element syntax or attribute syntax. And is normally set something like this:

OneWay binding causes changes to the source property to automatically update the target property, but changes to the target property are not propagated back to the source property. This type of binding is appropriate if the control being bound is implicitly read-only.

TwoWay binding causes changes to either the source property or the target property to automatically update the other. This type of binding is appropriate for editable forms or other fully-interactive UI scenarios.

OneTime causes the source property to initialize the target property, but subsequent changes do not propagate. This means that if the data context undergoes a change or the object in the data context changes, then the change is reflected in the target property. This type of binding is appropriate if you are using data where either a snapshot of the current state is appropriate to use or the data is truly static.

OneWayToSource is the reverse of OneWay binding; it updates the source property when the target property changes.

Default causes the default Mode value of the target property to be used.

Use the Binding.Mode property to specify the direction of the data flow. To detect source changes in one-way or two-way bindings, the source must implement a suitable property change notification mechanism such as INotifyPropertyChanged. For an example, see: How to: Implement Property Change Notification.

Change notification is such an important lesson to learn in databinding that we need to look at it right now. So, let's have a look at an example of using the interface INotifyPropertyChanged.

To support OneWay or TwoWay binding to enable your binding target properties to automatically reflect the dynamic changes of the binding source, your class needs to provide the proper property changed notifications; this is where INotifyPropertyChanged is used.

To implement INotifyPropertyChanged, you need to declare the PropertyChanged event and create the OnPropertyChanged method. Then, for each property you want change notifications for, you call OnPropertyChanged whenever the property is updated.

What Triggers Source Updates

Bindings that are TwoWay or OneWayToSource listen for changes in the target property and propagate them back to the source. This is known as updating the source. For example, you may edit the text of a TextBox to change the underlying source value. As described in the last section, the direction of the data flow is determined by the value of the Binding.Mode property of the binding.

However, does your source value get updated while you are editing the text or after you finish editing the text and point your mouse away from the TextBox? The Binding.UpdateSourceTrigger property of the binding determines what triggers the update of the source. The options available are as follows:

There are many properties that may be used within the Binding class, as such, I will not have time to cover all of them, though I shall attempt to go through the most common buts of syntax. As most binding will usually be set in XAML, I will be concentrating on the XAML syntax, though it should be noted that anything that can be done in XAML can also be done in C#/VB.NET code behind.

OK, so let's have a look at the basic syntax (we will cover more advanced stuff in the sections below).

The most basic form of binding is to create a binding that binds to a value of an existing element (this is covered in more detail below). I just wanted to introduce the syntax and go back and show you how to do the Binding.Mode and Binding.UpdateSourceTrigger stuff first.

So here is probably one of the simplest Bindings that you will see. This example has two buttons: the first button (btnSource) has a Yellow Background property. The second button uses the first button (btnSource) as the source for a Binding where the first button (btnSource) Background value is being used to set the second button's Background.

An Important Note

Recall from Part 2 that I mentioned that Binding was a markup MarkupExtension. As such, the XAML parser knows how to treat the { } sections. But really, this is just shorthand, that can (if you prefer) be expressed using the longer, more verbose, syntax as shown below:

<ButtonMargin="10,0,0,0"Content="Im bound to btnSource, using long Binding syntax"><Button.Background><BindingElementName="btnSource"Path="Background"/></Button.Background></Button>

This is a decision you will have to make yourself; me, personally, I prefer the { } syntax, though you don't get any intellisense help within Visual Studio if you do use the {} syntax.

When you set out to set up a Binding, there are several different things you need to consider:

What property do I want to bind to?

What property should we bind from?

Does it need to be OneWay or TwoWay etc.? If it needs to be a TwoWay/OneWayToSource Binding, was the source property a Dependency Property? It has to be to carry out a TwoWay/OneWayToSource Binding.

Once you know or have considered all this, it's really as easy as ABC. As part of the demo solution, you will find a project entitled "BindingToUIElements" which, when run, will look like the following:

This simple demo application shows three different Bindings going on. I will briefly discuss each of these now.

1. Simple Element Binding (Default Mode)

This simple example uses the first button's Background as the source value for the other two Buttons' Background.

3. TwoWay Binding Using UpdateSourceTrigger

This simple example uses two TextBoxes, where there is a TwoWayBinding.Mode applied, and the Binding.UpdateSourceTrigger is set to PropertyChanged, which means that the source of the Binding will be updated when the second TextBox's value changes.

The code for which is as follows:

<!-- Using UpdateSourceTrigger/Mode--><LabelContent="Using UpdateSourceTrigger/Mode"Margin="5,0,0,0"FontSize="14"FontWeight="Bold"/><StackPanelOrientation="Horizontal"Margin="10,10,10,10"Background="Gainsboro"><TextBlockTextWrapping="Wrap"Text="This uses TwoWay Binding and
UpdateSourceTrigger=PropertyChanged.Type
in one textbox then the other,
and see them update each other"Width="400"/><TextBoxx:Name="txtSource"Width="50"Height="25"Margin="5,0,0,0"/><TextBoxWidth="50"Height="25"Margin="5,0,0,0"Text="{Binding ElementName=txtSource,
Path=Text, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged }"/></StackPanel>

XML is used a lot these days, both for configuration information and data exchange, and indeed even for UI design. Remember, XAML is an XML derivative.

But that's not all we can use XML data for. We can in fact bind to XML data. This is fairly easy to do in XAML. We can either have the XAML hold the XML data (though this is probably not the norm), or use external XML files.

Either way, the normal proceeding is to use an XmlDataProvider within the XAML/code. Like I said earlier, I think most Bindings will be done in XAML, and I will stick to that.

As part of the demo solution, you will find a project entitled "BindingToXML" which, when run, will look like the following:

The top two sections of this demo app use XAML held XML data, and the bottom two use an external XML file.

XmlDataProvider Using XAML Held Data (Inline XML Data)

It is entirely possible to hold all the XML data within the XAML file, and use this data as a source for Binding. Let's see an example of this:

It can be seen from this example that we use an inline (in the XAML) XML dataset for the XmlDataProvider. And that we use the XmlDataProvider as the BindingSource for the ListBox. In this example, the first ListBox shows all Films/Titles as we are just fetching the Film/Title nodeset using the Binding.XPath=Film/Title, so we get all Titles shown.

The second ListBox is a bit fussier, and uses a bit of XPath notation to traverse the attribute axis and only fetches those nodes that have Year > 1991, so we get less nodes returned.

XmlDataProvider Using External XML File

As I say, it's going to be more common to use external XML files with the XmlDataProvider, which can be done as follows. Where the XmlDataProvider's Source property is set to the external XML file.

Using this arrangement is much the same as we saw before where we can use XPath to fetch all the nodes or use XPath to only match those nodes where the attribute matches the requirements. In this example, the second ListBox only shows "Mexican" restaurants from the XML file, using the following XPath:

Note: Using XML to provide Binding values is fine, but don't expect that you will be able to update XML simply by using a Binding.Mode set to TwoWay. That won't work. XML data binding is a simple one-way/not-updatable type of arrangement.

Binding to XLINQ

Although I'm not going to go into this, Beatriz The Binding Queen Costa has a good blog entry right here if you are curious.

Typically, WPF development will more than likely involve binding to an entire collection at some point. Now, this is very, very easy to do in WPF. As with most things, there are many ways to do this. I'll outline two possible ways, but of course, there will be more. I just like these ways, that's all.

One important thing to always keep in mind is change notification. Recall, we addressed that for individual classes by using the INotifyPropertyChanged interface. But what about Collections that will hold objects, what should we do about them?

Well, as luck would have it, these days, there is a nice ObserverableCollection that fills this spot quite nicely. This collection takes care of notifying the UI every time an element in the collection is added/removed. We still need to make sure that each of the held objects does its own change notification using the INotifyPropertyChanged interface. But by using ObserverableCollection and classes that implement INotifyPropertyChanged, we are sitting pretty, no change will pass us by.

As part of the demo solution, you will find a project entitled "BindingToCollections" which, when run, will look like the following:

So binding to such a collection becomes a snap. Here are two possible ways to do this using ListBoxes:

<Windowx:Class="BindingToCollections.Window1"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:BindingToCollections"WindowStartupLocation="CenterScreen"Title="Window1"Height="800"Width="800"><ScrollViewerHorizontalScrollBarVisibility="Auto"VerticalScrollBarVisibility="Auto"><StackPanelOrientation="Vertical"><!-- ListBox Source Set In Code Behind--><StackPanelOrientation="Vertical"><LabelContent="ListBox Source Set In Code Behind"Margin="5,0,0,0"FontSize="14"FontWeight="Bold"/><ListBoxx:Name="lstBox1"/></StackPanel></StackPanel></ScrollViewer></Window>

Binding to Collections in XAML

The second ListBox has its ItemSource set in XAML as follows:

<Windowx:Class="BindingToCollections.Window1"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:BindingToCollections"WindowStartupLocation="CenterScreen"Title="Window1"Height="800"Width="800"><Window.Resources><local:Peoplex:Key="people"><local:PersonPersonName="Freddy Star"/><local:PersonPersonName="Stick Head"/></local:People></Window.Resources><ScrollViewerHorizontalScrollBarVisibility="Auto"VerticalScrollBarVisibility="Auto"><StackPanelOrientation="Vertical"><!-- ListBox Source Set By Using Resources --><StackPanelOrientation="Vertical"><LabelContent="ListBox Source Set By Using Resources"Margin="5,0,0,0"FontSize="14"FontWeight="Bold"/><ListBoxx:Name="lstBox2"ItemsSource="{Binding Source={StaticResource people}}"/></StackPanel></StackPanel></ScrollViewer></Window>

You can see that we have an instance of the People object directly in the XAML, within a resources section, and that the declared People object has several children of type Person. This is all thanks to the XAML parser which knows that children should be added using the Add() method of the ObserverableCollection.

I should point out that these examples are merely demonstrating how to Bind to collections. In a production system, the collection would probably be part of a BAL layer/ or maybe part of a Model within a MVC/MVVM pattern. I am going for quick and dirty to get the point across.

One other thing that I would like to bring your attention to is the rendering of the items within the ListBox. See how they simply show "BindingToCollection.Persons" as plain text.

This is obviously not the desired effect, but happens because WPF does not know what properties to show and how they should be shown for a Person object. This will be the subject of my next article on Templates. I won't write any more about this, but just know that we can change the way a data item looks using a DataTemplate. If you really can't wait, you can have a look at these links:

Imagine a situation where we have a bound data value that we wish to format in some way, say by using a short date format instead of a long date format. Up until now, we have simply used the raw Binding value. This wouldn't be possible, and we would have to make sure the bound value has what we want to display. Luckily, WPF has a trick up its sleeve. We can use a class that implements the IValueConverter interface to provide a new value for the binding.

ValueConverters are like the sprintf of the WPF world. You can use a ValueConverter to literally provide a new object to a Binding. This may be an object of the same type as the original object, or a totally new object. For example, in WPF, there is a principle of a Freezable Object which is an immutable object. If you try and animate a Frozen object, you will have problems. I have in the past circumnavigated this issue with using a Clone ValueConverter to provide a cloned object to a Binding which is then used in an animation.

But more typically, you may use ValueConverters for small formatting changes.

ValueConverters sit between the source value and the bound target property, and their sole purpose is to take a value and supply a different value.

The IValueConverter interface contains the following methods that must be implemented:

Which is used to convert from the target object back to the source. This will be used where a Bindings Binding.Mode has been set to TwoWay or OneWayToSource. More often than not, this will not be used, and will simply throw an exception.

So how do we use these ValueConverters in our code? Well, quite simply, we use the normal Bindings expression, but we also state which converter to use for the Binding.Converter property. Let's see an example, shall we?

As part of the demo solution, you will find a project entitled "ValueConverters" which, when run, will look like the following:

This small example actually uses two ValueConverters, the top one converts from words to a Brush that is used to color a Rectangle. The second value converter uses an explicitly set DataContext in the code-behind where two Labels have their DataContext set to a new DateTime. Let's see the code:

So far we've looked at binding to values/other elements/XML etc., and seen how we can convert values. Which is good. But one of the main concerns of using Binding is validating what data is entered, especially when we have a Binding.Mode property set to TwoWay or OneWayToSource. We really need to make sure that we only allow valid data to be sent back to a source object. Not only is it the right thing to do, but it ensures that we don't send back rubbish data to our persistence store (database/file etc/). So how are we going to do that? We need some sort of validation applied to our Bindings.

Luckily, Microsoft knew about this, and have equipped us with the necessary ammunition to create good, well-behaved, validated Databindings. There are three main ways that validation may be performed, and we shall have a look at each of them below.

As part of the demo solution, you will find a project entitled "Validation" which, when run, will look like the following:

Visual Validation Changes

As part of the attached "Validation" project, I have included some Styles. Which is an area that we have not yet covered. There is no way out of this. The things you need to know for the moment are that a TextBox entry that is invalid will cause the associated TextBox to have its visual appearance changed by the use of a Style or a Template. And the other thing is how the TextBox.ToolTip is showing the correct validation message. Well, this is also done via some clever binding, which is as follows:

As I say, I don't want to get too bogged down with Styles/Templates as they are the discussion of the next article, but I think that this one element deserves a mention.

Exception Based Validation

Probably the easiest way to use validation in Binding is to use the Exception based validation rule. Which basically means if an Exception is seen while trying to update a bound property, we can use the Exception to inform the user. Typically, this would be done by showing a message on a tooltip and changing the TextBox visual as previously discussed. If we have a small test class to bind to as follows:

The important thing to note is that Binding.ValidatesOnExceptions=True means that the WPF inbuilt ExceptionValidationRule will be used to create the appropriate validation message that will be shown in TextBox.Tooltip.

Custom ValidationRules Based Validation

Custom ValidationRules is similar in principle to the inbuilt ExceptionValidationRule, but this time, we are using our own ValidationRule to create the appropriate validation messages. Here is an example of a custom ValidationRule, where the value entered for the binding must be a DateTime in the future.

The important thing to note here is that because we needed to add a new FutureDateValidationRule to Binding.ValidationRules, we needed to use the Property as Elements syntax.

.NET 3.5 Way Using IDataErrorInfo

With the release of .NET 3.5 came LINQ, oh and also a few improvements to WPF. One of which is a new interface called IDataErrorInfo which shifted where some of the validation was performed. It moved it from separate validation classes back into the actual business object themselves.

Let's see an example of a simple class that implements the IDataErrorInfo interface:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace Validation
{
///<summary>/// This is the new .NET 3.5 method where each
/// Business Object has its own validation
/// using the IDataErrorInfo interface
///</summary>publicclass Person : IDataErrorInfo
{
publicint Age { get; set; }
publicstring Name { get; set; }
public Person()
{
this.Age = 0;
this.Name = "sacha";
}
#region IDataErrorInfo Members
publicstring Error
{
get
{
returnnull;
}
}
///<summary>/// Examines the property that was changed and provides the
/// correct error message based on some rules
///</summary>///<paramname="name">The property that changed</param>///<returns>a error message string</returns>publicstringthis[string name]
{
get
{
string result = null;
//basically we need one of these blocks
//for each property you wish to validate
switch (name)
{
case"Age":
if (this.Age < 0 || this.Age > 150)
{
result = "Age must not be less than 0 or greater than 150.";
}
break;
case"Name":
if (this.Name == string.Empty)
{
result = "Name can't be empty";
}
if (this.Name.Length > 5)
{
result = "Name can't be more than 5 characters";
}
break;
}
return result;
}
}
#endregion
}
}

And here is the VB.NET version:

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.ComponentModel
'''<summary>''' This is the new .NET 3.5 method where
''' each Business Object has its own validation
''' using the IDataErrorInfo interface
'''</summary>PublicClass Person
Implements IDataErrorInfo
Private m_Age AsIntegerPrivate m_Name AsStringPublicProperty Age() AsIntegerGetReturn m_Age
EndGetSet(ByVal value AsInteger)
m_Age = value
EndSetEndPropertyPublicProperty Name() AsStringGetReturn m_Name
EndGetSet(ByVal value AsString)
m_Name = value
EndSetEndPropertyPublicSubNew()
Me.Age = 0Me.Name = "sacha"EndSub#Region"IDataErrorInfo Members"PublicReadOnlyProperty [Error]() AsStringImplements _
System.ComponentModel.IDataErrorInfo.ErrorGetReturnNothingEndGetEndProperty'''<summary>''' Examines the property that was changed and provides the
''' correct error message based on some rules
'''</summary>'''<paramname="Name">The property that changed</param>'''<returns>a error message string</returns>DefaultPublicReadOnlyProperty Item(ByVal Name AsString)
AsStringImplements System.ComponentModel.IDataErrorInfo.Item
'Default Public ReadOnly Property Item(ByVal name As String) As String
GetDim result AsString = Nothing'basically we need one of these blocks
'for each property you wish to validate
SelectCase Name
Case"Age"IfMe.Age < 0OrElseMe.Age > 150Then
result = "Age must not be less than 0 or greater than 150."EndIfExitSelectCase"Name"IfMe.Name = String.Empty Then
result = "Name can't be empty"EndIfIfMe.Name.Length > 5Then
result = "Name can't be more than 5 characters"EndIfExitSelectEndSelectReturn result
EndGetEndProperty#End Region
EndClass

Basically, the interface allows us to validate the property that was changed using the public string this[string name] syntax. The XAML is a little different this time, where the Binding no longer needs to use a seperate validation class, so we can simply use the shorthand XAML syntax, the one with the { } braces. Again, if you prefer the longer, more verbose syntax, you can do that also.

Notice that this time we have set Binding.ValidatesOnDataErrors=True; this means that the DataErrorValidationRule will be included, which uses the IDataErrorInfo implementation we discussed.

Warning: Beware of Tabs

I recently got a rather cool email from Karl Shifllet, warning of a bug with validation error disappearing when you use tabs in WPF. You should familiarise yourself with Karl's blog entry about this.

We're Done

There is more to Databinding than I have covered here; for example, I have not covered grouping/sorting/filtering etc., and there will be databinding points and syntax that I have missed. I leave these areas as an exercise for the reader. This article was meant as an introduction to Databinding; hope you enjoyed it. If you liked it, please vote for it and leave a comment, and maybe read the next article in this series. Thanks!

Comments and Discussions

Loved the tut, but it stopped short after the class. Maybe for future update try to finish an example before going on to the next. Just a bit of a let down that you started to teach class binding and then didn't add the actual binding in Xaml after teaching how to make the class...

would love some help to get the last of the information for awesome tut

This is a really good article for styles/templates. These days,I'm learning WPF because of one project I'm working on. I had MFC/Windows Forms experiences, now I turns to WPF world, in the UI development, WPF is really easy and intuitive at my first glance.So, I have spent days on MSDN articles, but only reading MSDN is not enough to make all things(particularly for Styles/templates) clear, after reading your post, I think it is easier than MSDN.By combining your articles with MSDN and other guys' post. It help me a lot, especially in the data binding and styles/templates, personally, I think those two items are difficult piece of WPF.

Excellent article... easy to follow, very happy with the supplemental links provided for additional learning. I've been following this series from the beginning, and so far this Databinding section is my favorite article. Really helping me get on my feet as I learn WCF, so thanks for taking your time to create such a well organized series.

Funny you should mention that - I was just going to look into the new 4.0 Threading changes to keep my UI from freezing, while hoping to move on from relying on the BackgroundWorker class for everything. I'll definitely check it out.

I'm trying to learn all the knowledge you provide to us and I try to add some functionalities of my own.
By example, I want to disable a "Save" menu item if there is an error in the form. But I don't have find how to know if there is an error on the form. Is there a possibility to check the error count ?

I'm already using the IDataErrorInfo interface. My problem is to bind the "Enable" property of a menu item to something like the error count on my page. If I have at least one error provided with IDataErrorInfo, so my menu item is disabled.

I am trying to use my external XML file that contains a reference to a DTD, but I do not have the DTD. Is there any way to set a property or turn off the checking of external references when using the XmlDataProvider?

The XmlDataProvider Using External XML File does not work if the XML file contains a link to a dtd that does not exist. So no information displays at all even though everything is perfectly correct.

I figured out how to load an XML file without having the associated DTD. I could not find a pure XAML way to do this, but it's pretty simple using the code behind. The code behind creates a new XmlDocument and sets the XmlResolver property to Nothing. Then find the XAML Resource where you want to set the XML. Set the Document property of the XmlDataProvider to this new XmlDocument.

' give your XAML XmlDataProvider a key... such as "XMLdata"
Dim existing As XmlDataProvider = FindResource("XMLdata")
' then set the Document property of the XmlDataProvider to the XmlDocument
existing.Document = reader

Hope this helps others that come across this issue.

If anybody knows a pure XAML way to load XML files but not resolve the DTD, please share!

maybe someone else already pointed it out,
or I didn't read all replies to your article well enough, but here goes my two cent's worth anyway:

-----

In your example where you 'bind the listbox to person objects', you state that:

"One other thing that I would like to bring your attention to is the rendering of the items within the ListBox. See how they simply show "BindingToCollection.Persons", as plain text. "

I noticed - while experimenting with the code - that this is typically the output of the generic 'ToString()' method
on the 'Person' object, which is used internally to fill up the listbox with rather un-useful names.

So if you override the person's 'ToString()' method like this:

public override string ToString()
{
return name;
}

We can simply have a more useful string showing up in the listbox... the actual names of the persons.
neat and ultra simple, no?

I thought I'd just mention it, because it's the most simple way of actually getting your data out there, without any need for convertors or anything.
(stating the almost obvious, I guess. but hey, I'm just learning