There are a lot of situations when you need to bind ConverterParameter value.
Imagine that you have Receipt class with two fields: amount and currency type. And you need to format amount string to something like $1,000.00 or ¥1,000.00 depending on currency type. So the good idea is to use converter to do formatting.
The good way is to have something like AmountFormatter which takes amount and currency type and does the formatting.
Current version of the Silverlight disallowing us to bind Converter Parameter value. But we could pass whole Reciept object to the formatter and take amount and currency type from it directly. Such formatter could look like this:
public class AmountConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var receipt = value as Receipt;
if (receipt != null)
{
return String.Format("{1}{0:0,0.0}", receipt.Amount, receipt.CurrencyChar);
}
return value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
...
}
}
This method is not good cause we tide converter and particular class (in our case it is Receipt). But what could we do?
Ok, we want to have a reusable converter. But we need to pass several values to it at the same time. Then lets simply define an interface which converter is expecting to get:
public class AmountConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var data = value as IConverterData
if (data != null)
{
return String.Format("{1}{0:0,0.0}", data.Value, data.CurrencySign);
}
return value.ToString();
}
...
public interface IConverterData
{
string Value { get; set; }
string CurrencySign { get; set; }
}
}
Now to prepare Receipt class to be used in conjunction with AmountConverter we just need to implement AmountConverter.IConverterData interface.
And the usage will look like this:
<TextBlock Text="{Binding Converter={StaticResource AmountConverter}}"/>
Please not what we binds to the whole object here.