Silverlight 5 Beta were just announced. This post opens a series of “What’s New” posts about the new version. This post focuses on Data Binding and data handling enhancements.
One of the most interesting features is Data Binding debugging support, which enables to place a breakpoint into XAML (databinding expression) and inspect it at the runtime. During the runtime, when the code hits breaking point it just stops as managed code does and enables inspection of all the properties related to the binding expression.

Very helpful, especially with complex data bindings!
The next very helpful feature arrives directly from the “Big Brother” of Silverlight, the WPF. It called implicit Data Templates. From now on, Silverlight applications could define implicit (the default) Data Template for particular type and it will be applied on the runtime while presenting the specific type. Consider the following data type (Employee) defined as the following:
public class Employee : INotifyPropertyChanged
{
private int id;
public int ID
{
get { return id; }
set
{
id = value;
Utils.NotifyPropertyChanged("ID", this, PropertyChanged);
}
}
private string firstName;
public string FirstName
{
get { return firstName; }
set
{
firstName = value;
Utils.NotifyPropertyChanged("FirstName", this, PropertyChanged);
}
}
private string lastName;
public string LastName
{
get { return lastName; }
set
{
lastName = value;
Utils.NotifyPropertyChanged("LastName", this, PropertyChanged);
}
}
private DateTime birthday;
public DateTime Birthday
{
get { return birthday; }
set
{
birthday = value;
Utils.NotifyPropertyChanged("Birthday", this, PropertyChanged);
}
}
private float salary;
public float Salary
{
get { return salary; }
set
{
salary = value;
Utils.NotifyPropertyChanged("Salary", this, PropertyChanged);
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
While the data class is pretty simple, to present it correct in XAML we need to define some Data Template. In Silverlight 5 the implicit data template definition will enable to create “default” look for specific data type. This will presented in all usages of the data if will not overridden by local definition. Consider the following DataTemplate – pay attaention to lack of the x:Name definition:
<DataTemplate DataType="local:Employee">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height=".5*"/>
<RowDefinition Height=".5*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock FontSize="15">
<Run Text="{Binding FirstName}"/>
<Run Text=","/>
<Run Text="{Binding LastName}"/>
</TextBlock>
<TextBlock FontSize="12" Grid.Row="1">
<Run Text="Salary: "/>
<Run FontStyle="Italic" Text="{Binding Salary}"/>
</TextBlock>
<TextBlock FontSize="12" Grid.Row="2">
<Run Text="Birthday: "/>
<Run FontStyle="Italic" Text="{Binding Birthday, StringFormat=dd/MM/yyyy}"/>
</TextBlock>
</Grid>
</DataTemplate>
From now on, the only thing needed to present the list of employees is to bind to the collection:
<ListBox ItemsSource="{Binding Employees}" MaxHeight="400"/>
The item will be presented as defined in the default Data Template:

To override the default representation, just create additional Data Template for the type and provide it an x:Key.
Next feature helps to deal with the questions like “how I could style the DataTemplate/ControlTemplate according to the context I’m using it?”…
Let’s assume you have 2 pages with completely different background. How to much the visual representation of some part to the page? What if the same part is used in multiple locations with different (for example) backgrounds? To solve this problem, Silverlight 5 has a new feature (once again, long awaited addition from WPF) called RelativeSource. It enables to bind to a property on the control that contains it.
In my case I have a list of employees in different divisions and this list could be presented in a few different pages (with slightly different look and feel). I’d like to match the Division Name to the page color scheme:
<DataTemplate DataType="local:Division">
<StackPanel Orientation="Vertical" >
<TextBlock Foreground="{Binding RelativeSource={RelativeSource AncestorType=ContentControl},
Path=Background}" FontSize="20" FontFamily="Trebuchet MS" Text="{Binding DivisionName}"/>
<ListBox ItemsSource="{Binding Employees}" MaxHeight="400"/>
</StackPanel>
</DataTemplate>
The interesting part is RelativeSource, which enables to specify the AncestorType, AncestorLevel and the Mode in order to identify the control in the parts tree we are looking for. In this example the Foreground property of the TextBLock will be taken from ContentControl.Background anywhere above StackPanel in the Visual Tree.
This relative source could also point on the control itself. Consider the following code:
<TextBox Text="#FF55FFCC" Grid.Row="0" Style="{StaticResource textStyle}"
Background="{Binding Text, RelativeSource={RelativeSource Self}}"
Width="200"/>
In this case background of the TextBox changes according to the value of text. The Relative Source points onto “Self”, meaning the control itself – one of the properties of the control.
Consider the following binding expression:
<Border Grid.Column="0" BorderThickness="2" BorderBrush="Black" CornerRadius="2" Margin="2"
Background="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=UserControl}, Path=Background}"
Height="100"
Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=2, AncestorType=Grid},
Path=Width, Converter={StaticResource halfSizeConverter}}">
The first RelativeSource travels up on the VisualTree and looks for UserControl instance (first which will be found), the second RelativeSource takes the value from Grid exactly 2 levels above.
Next improvement is an ability to databind with style setters. Consider multiple projects in the big company, with company’s color scheme and various font definitions defined by designers as resource. Those values should be used by all applications, but each application could define slightly different combination of them. IN such case a new feature of Data Binding in style setters comes at the right place. Consider the following definition in some general resource dictionary (used in multiple applications and added to the project as a shared source):
<SolidColorBrush x:Key="textBrush" Color="DarkGreen"/>
<sys:String x:Key="textFont">Trebuchet MS</sys:String>
<sys:Double x:Key="textFontSizeHuge">60</sys:Double>
Those definitions should be used in specific application and could be changed by company’s designer from single place:
<Style TargetType="TextBox" x:Key="textStyle">
<Setter Property="FontFamily" Value="{StaticResource textFont}"/>
<Setter Property="Foreground" Value="{StaticResource textBrush}"/>
<Setter Property="FontSize" Value="{Binding Source={StaticResource textFontSizeHuge}, Converter={StaticResource halfSizeConverter}}"/>
</Style>
Now, when the definitions of font name, font size, etc. are changed the application will pick them up (after re-compiling).
The last, but not least is the ability to create our own Markup Extensions. This feature also arrived from WPF and allow code to be run at XAML parse time for both properties and event handlers.
Consider the following code snippet:
public static string StrVal = "Hello from static variable!";
Before markup extensions, there were no way to databind to the static variables. Now, with Markup Extensions it is possible to write XAML like the following:
<TextBlock Text="{local:Static TypeName=Utils.StrVal}"/>
Let’s see how it were built. Custom markup extension is a public class derived from MarkupExtension base class and in simple case have to override only one function:
public override object ProvideValue(IServiceProvider serviceProvider);
Let’s see the simple implementation first:
public class NowExtension : MarkupExtension
{
public string Format { get; set; }
public NowExtension()
{
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
string retVal = "";
switch (Format)
{
case "F":
retVal = DateTime.Now.ToShortDateString();
break;
case "FF":
retVal = DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + ", " + DateTime.Now.DayOfWeek;
break;
case "FFF":
retVal = DateTime.Now.ToLongDateString();
break;
default:
retVal = DateTime.Now.ToShortDateString();
break;
}
return retVal;
}
}
This class returns formatted Date representation by given parameters. Note, that the usage omits the “Extension” part of the class name. The usage of such class (NowExtension) in XAML:
xmlns:local="clr-namespace:DataBindingImprovements"
…
<TextBlock Text="{local:Now Format=FFF}"/>
At the runtime when the ProvideValue method executes it provides the current date formatted according to the parameter.
Now let’s get back to the static variable case. The markup extension in this case is slightly longer, since we need to resolve the static value at the runtime from its text/name:
public class StaticExtension : MarkupExtension
{
Type t;
FieldInfo f;
public StaticExtension()
{ }
private string typeName;
public string TypeName
{
get { return typeName; }
set
{
typeName = value;
initializeInfo(typeName);
}
}
private void initializeInfo(string typeName)
{
string[] val = typeName.Split(new char[] { '.' });
t = Type.GetType(GetType().Namespace + "." + val[0], false, true);
if (null != t)
f = t.GetField(val[1], BindingFlags.Static | BindingFlags.Public);
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (null != f)
return f.GetValue(null);
else
return null;
}
}
The code is pretty self-describing, and the usage is the following:
<TextBlock Text="{local:Static TypeName=Utils.StrVal}"/>
Now we could use the static variables from XAML.

That’s it for the first part.
The sources for the application I used to show the features could be found here.
In the next part I’ll show the tear-off windows support in out-of-browser applications.
Stay tuned,
Alex