This is our solution. I hope I understood your problem that you want to change for example DateTime
?
The Converter
is a simple IValueConverter
which convert the value to the current Language. Translator
is a static class which holds (for example) the CurrentLanguage
(en-en / de-de) as string
.
The Behavior
is needed to update the Bindings if the language has changed. We only need this implementation 3-4 times in the hole program, because it is only for the DateTime
formating. All other texts are hold in a dynamic Resource..
But I think for your needs the Behavior
is the right one.
Converter
public class CultureConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
DateTime dateTime;
if(DateTime.TryParse(value.ToString(), out dateTime))
{
if(parameter != null)
{
return dateTime.ToString(parameter.ToString(), new CultureInfo(Translator.CurrentLanguage));
}
return dateTime.ToString(new CultureInfo(Translator.CurrentLanguage));
}
return null;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
Behavior
public class CultureConverter : Behavior<FrameworkElement>
{
private FrameworkElement _HostingControl;
private DependencyProperty _HostingControlDependencyProperty;
protected override void OnAttached()
{
base.OnAttached();
_HostingControl = AssociatedObject;
_InitHostingControl();
Translator.LanguageChanged += Translator_LanguageChanged;
}
protected override void OnDetaching()
{
Translator.LanguageChanged -= Translator_LanguageChanged;
base.OnDetaching();
}
private void Translator_LanguageChanged(string languageCode)
{
if(_HostingControlDependencyProperty != null)
_HostingControl.GetBindingExpression(_HostingControlDependencyProperty).UpdateTarget();
}
private void _InitHostingControl()
{
if(_HostingControl is TextBlock)
{
_HostingControlDependencyProperty = TextBlock.TextProperty;
}
else if (typeof(TextBox) == _HostingControl.GetType())
_HostingControlDependencyProperty = TextBox.TextProperty;
}
XAML
<Window.Resources>
<XamlConverter:CultureConverter x:Key="CultureConverter"/>
<Window.Resources>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock
Text="{Binding CreatedOn, ConverterParameter=f, Converter={StaticResource CultureConverter}, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Behaviors>
<Behaviors:CultureConverter/>
</i:Interaction.Behaviors>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
Preview