I'm not that firm with MVVM and I hope someone can help me with this. I'm using C#/XAML for Windows Phone 8. Usually my ViewModel provides a property MyProperty and I'd bind it like this:
<TextBlock Text="{Binding MyProperty, StringFormat='This Property: {0}'}" FontSize="30" />
The problem is that in my view model there are some data bound properties which are localized by different strings. E.g. let's say you have a date - either upcoming or aleady passed. This date shall be localized like this:
upcoming: "The selected date {0:d} is in the future"
passed: "The selected date {0:d} already passed"
Is it possible to do the localization in the XAML? Or is there another possiblity to avoid localized strings in the viewmodel? (Is an avoidance of localized strings in the viewmodel desirable after all?)
Thanks in advance!
Regards, Marc
Try using a IValueConverter
Example:
Xaml:
<Window x:Class="ConverterSpike.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ConverterSpike="clr-namespace:ConverterSpike"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ConverterSpike:DateStringConverter x:Key="DateConverter" />
</Window.Resources>
<Grid>
<TextBlock Text="{Binding MyProperty, Converter={StaticResource DateConverter}}" />
</Grid>
</Window>
Converter:
using System;
using System.Globalization;
using System.Windows.Data;
namespace ConverterSpike
{
public class DateStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return string.Empty;
var date = value as string;
if (string.IsNullOrWhiteSpace(date)) return string.Empty;
var formattedString = string.Empty; //Convert to DateTime, Check past or furture date, apply string format
return formattedString;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}