Silverlight 4: New features overview (Part 5) – DataBinding improvements
Silverlight 4 introduces improvements in DataBinding. between the improvements are IDataErrorInfo support, ability to bind to DataObjects, StringFormat, TargetNullValue, FallbackValue support and many others.
This post will show how to use StringFormat, TargetNullValue and FallbackValue while databinding.
For show the new features I’ve created sample application –> it will display values bounded to number of DependencyProperties defined in code behind.
In code behind I’ve created number of Dependency Properties to bind to:
public DateTime DateValue
{
get { return (DateTime)GetValue(DateValueProperty); }
set { SetValue(DateValueProperty, value); }
}
// Using a DependencyProperty as the backing store for DateValue. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DateValueProperty =
DependencyProperty.Register("DateValue", typeof(DateTime), typeof(MainPage), null);
public float CurrencyValue
{
get { return (float)GetValue(CurrencyValueProperty); }
set { SetValue(CurrencyValueProperty, value); }
}
// Using a DependencyProperty as the backing store for CurrencyValue. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CurrencyValueProperty =
DependencyProperty.Register("CurrencyValue", typeof(float), typeof(MainPage), null);
public string NullableFiled
{
get { return (string)GetValue(NullableFiledProperty); }
set { SetValue(NullableFiledProperty, value); }
}
// Using a DependencyProperty as the backing store for NullableFiled. This enables animation, styling, binding, etc...
public static readonly DependencyProperty NullableFiledProperty =
DependencyProperty.Register("NullableFiled", typeof(string), typeof(MainPage), null);
Now let’s see the first sample – StringFormat. It allows to format the value received from bounded property:
<StackPanel Orientation="Horizontal" Margin="5">
<TextBlock Text="StringFormat Sample:"/>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding DateValue, StringFormat='dddd, dd-MMMM-yyyy'}"/>
<TextBlock Text="{Binding CurrencyValue, StringFormat=P}"/>
<TextBlock Text="{Binding CurrencyValue, StringFormat=Monthly Income \{0:C\}}"/>
</StackPanel>
</StackPanel>
The TargetNullValue. The value is used in the target when the value of the source is null:
<StackPanel Orientation="Horizontal" Margin="5">
<TextBlock Text="TargetNullValue Sample:"/>
<TextBlock Text="{Binding NullableFiled, TargetNullValue='The value is NULL'}"/>
</StackPanel>
The last one – FallbackValue. This value is used when data binding engine is unable to return the value. The most common case for this is wrong source or path:
<StackPanel Orientation="Horizontal" Margin="5">
<TextBlock Text="FallbackValue Sample:"/>
<TextBlock Text="{Binding NonExistingField, FallbackValue='The path is not valid!'}"/>
</StackPanel>
Working application:
Sources here.
Stay tuned for more.
Alex