If you require to format bound object properties such as dates or values inside you XAML-code, the following converter might be useful. The converter uses the String.Format function, whereas the value and the format-String are passed as parameters.
First the Visual Basic.NET implementation:
Imports System.Globalization
Imports System.Windows.Data
Public NotInheritable Class FormatConverter
Implements IValueConverter
Public Function Convert(ByVal value As Object, ByVal targetType As System.Type,
ByVal parameter As Object, ByVal culture As CultureInfo) As Object
Implements IValueConverter.Convert
Dim formatString As String = parameter
If formatString IsNot Nothing Then
Return String.Format(culture, formatString, value)
Else
Return value.ToString()
End If
End Function
Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type,
ByVal parameter As Object, ByVal culture As CultureInfo) As Object
Implements IValueConverter.ConvertBack
Return Nothing
End Function
End Class
And here the same in C#:
using System.Globalization;
using System.Windows.Data;
public sealed class FormatConverter : IValueConverter
{
public object Convert(object value, System.Type targetType, object parameter, CultureInfo culture)
{
string formatString = parameter;
if (formatString != null) {
return string.Format(culture, formatString, value);
}
else {
return value.ToString();
}
}
public object ConvertBack(object value, System.Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
In order to use it, you have to add a new resource to your page/window:
<Page.Resources>
<YOURASSEMLY:FormatConverter x:Key="datetimefomatter"/>
</Page.Resources>
So let’s assume, we got a bound object with the property “RegDate” (of type Date) and want to display this date in a certain form (here a common German representation) inside a TextBlock.
<TextBlock Text = "{Binding Path=RegDate,
Converter={StaticResource datetimefomatter},
ConverterParameter='Registration Date: \{0:dd. MMM yyyy\}'}">
</TextBlock>
You can use any data types, values and format strings accepted by the String.Format function.