With the following code, although Text property is bound to a DateTime source property, I noticed WPF seems to automatically convert the text to a DateTime, without me needing to write a ValueConverter. Can someone please shed some light on how this is done
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WpfApplication1="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525"
>
<StackPanel>
<DatePicker Height="25" Name="datePicker1" Width="213" Text="{Binding Path=DueDate,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</Window>
public class P
{
private DateTime? dueDate = DateTime.Now;
public DateTime? DueDate
{
get { return dueDate; }
set
{
dueDate = value;
}
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
P p = new P();
this.DataContext = p;
}
}
It is using the
DateTimeTypeConverterfrom the Base Class Library (EDIT: Well, it could have used a TypeConverter however it appears that from @DeviantSeev’s answer that they did not).There ‘default’ converters you are talking about are actually
TypeConverters(MSDN) and they have been a part of the .NET Framework since v2.0 and they are used through-out the Base Class Libraries. Another example of TypeConverters in WPF is theThicknessTypeConverterforPadding,Margin, andBorderThicknessproperties. It converts a comma-delimited string to aThicknessobject.There are plenty of articles available if you want to understand them further.
There are two parts to using a
TypeConverter– implementation of the class and then marking up your properties/types withTypeConverterAttribute.For example, I recently had a custom control that required a
char[]that I wanted to set fromXamllike so:Usage
Implementation
When to use a
TypeConverter?You can only use
TypeDescriptorsif you are writing a custom control as you need to be able to mark-up the property with theTypeDescriptorAttribute. Also I would only useTypeConverterif the conversion is rather a straight-forward – as in the example above where I have a string and want achar[]– or if there are multiple possible formats that I want to convert from.You write
IValueConverterwhen you want more flexibility on how the value to converted by driving it by data or a passing a parameter. For example, a very common action in WPF is converting abooltoVisibility; there are three possible outputs from such a conversion (Visible,Hidden,Collapsed) and with only two inputs (true,false) it difficult to decide this in aTypeConverter.In my applications, to achieve this two inputs to three output problem I have written a single
BoolToVisibilityConverterwith aTrueValueandFalseValueproperties and then I instance it three times in my globalResourceDictionary.I’ll post the code sample tomorrow morning, I don’t it in front of me right now..