July 13, 2012 09:45 by
Scott
Silverlight 5 Beta brings the enormously useful ability to set a break point in your Xaml where you have a data binding. This can greatly simplify debugging and fixing binding issues.
To see this, create a new Silverlight 5 project and set up the Xaml to have 5 rows and 2 columns. Place the title in the first row (spanning both columns) and prompts in the next 4 rows. The prompts are
- FullName
- Address
- Phone
- Email
Add four TextBlocks in the second column to display the values that will correspond to these prompts. The Xaml for the four prompts looks like this:
<TextBlock
Grid.Column="1"
Grid.Row="1"
Margin="5"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Text="{Binding FullName}" />
<TextBlock
Grid.Column="1"
Grid.Row="2"
Margin="5"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Text="{Binding Address}" />
<TextBlock
Grid.Column="1"
Grid.Row="3"
Margin="5"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Text="{Binding PhoneNumber}" />
<TextBlock
Grid.Column="1"
Grid.Row="4"
Margin="5"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Text="{Binding Email}" />
To make this work, of course, we need a class and an instance to bind to. Begin by creating a new class, Person,
public class Person
{
public string FullName { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
In MainPage.xaml.cs create an instance of Person, and set that instance to be the data context for the bindings,
public MainPage()
{
InitializeComponent();
var per = new Person()
{
FullName = "Jesse Liberty",
Address = "100 Main Street, Boston, MA",
Email = "[email protected]",
Phone = "617-555-1212"
};
this.DataContext = per;
}
When you run this you’ll find that three of the four bindings work well, but the phone number is not displayed. Set a break point in the Xaml folder on the binding for the PhoneNumber and run the application. When you hit the break point examine the locals window as shown in the illustration to the below.
Note that there is an error message. By clicking on the message you can open a text reader for the entire error message, as shown in the next figure to the below.
The error message indicates that there is no property PhoneNumber in the type Person, and sure enough, a quick check of the code shows that the property is just Phone.
Change the binding from PhoneNumber to Phone and the program works as expected.