Articles → Silverlight → IValueConverter in Silverlight
IValueConverter in Silverlight
Software requirement
Prerequisite knowledge
Binding source Vs binding target
IValueConverter interface
Convert method
public object Convert(object value, Type targetType, object parameter,System.Globalization.CultureInfo culture)
ConvertBack method
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
ConvertParameters attribute
Creation of date convertor
public class DateConvertor : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
object returnValue = new object();
if (value != null)
{
returnValue = String.Format("{0:ddd, MMM d, yyyy}", value);
}
else
{
returnValue = String.Format("{0:ddd, MMM d, yyyy}", DateTime.Now);
}
return returnValue;
}
public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
object returnValue = new object();
if (value != null)
{
DateTime dt = DateTime.MinValue;
if (DateTime.TryParse(value.ToString(), out dt))
{
returnValue = String.Format("{0:ddd, MMM d, yyyy}", value);
}
else
{
returnValue = String.Format("{0:ddd, MMM d, yyyy}", DateTime.Now);
}
}
else
{
returnValue = String.Format("{0:ddd, MMM d, yyyy}", DateTime.Now);
}
return returnValue;
}
}
View creation
<UserControl x:Class="ConverterSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyConvertorClass">
<UserControl.Resources>
<local:ConverterSampleViewModel x:Key="viewmodel"></local:ConverterSampleViewModel>
<local:DateConvertor x:Key="MyConvertor"></local:DateConvertor>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding Source={StaticResource viewmodel}}">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Button Content="Click Me" Grid.Row="1" Command="{Binding ClickMeButtonCommand}" Height="50" Width="100"/>
<TextBox Width="200" Height="50"
Text="{Binding DateFormatProp,Converter={StaticResource MyConvertor},Mode=TwoWay}"/>
</Grid>
</UserControl>
Text="{Binding DateFormatProp,Converter={StaticResource MyConvertor}
Viewmodel creation
Public class ConverterSampleViewModel : ViewModelBase
{
private DateTime _DateFormatProp;
private readonly ICommand _clickMeButtonCommand;
public ConverterSampleViewModel()
{
this._clickMeButtonCommand = new DelegateCommand(this.ClickMeButtonClickEvent);
}
public void ClickMeButtonClickEvent()
{
// Add a time
DateFormatProp = DateTime.Now;
}
public DateTime DateFormatProp
{
get
{
return _DateFormatProp;
}
set
{
_DateFormatProp = value;
OnPropertyChanged("DateFormatProp");
}
}
public ICommand ClickMeButtonCommand
{
get
{
return this._clickMeButtonCommand;
}
}
}
Output
Click to Enlarge