Is there a way to chain multiple value converters in XAML?
Solution 1
I used this method by Gareth Evans in my Silverlight project.
Here's my implementation of it:
public class ValueConverterGroup : List<IValueConverter>, IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return this.Aggregate(value, (current, converter) => converter.Convert(current, targetType, parameter, culture));
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
Which can then be used in XAML like this:
<c:ValueConverterGroup x:Key="InvertAndVisibilitate">
<c:BooleanInverterConverter/>
<c:BooleanToVisibilityConverter/>
</c:ValueConverterGroup>
Solution 2
Found exactly what I was looking for, courtesy of Josh Smith: Piping Value Converters (archive.org link).
He defines a ValueConverterGroup
class, whose use in XAML is exactly as I was hoping for. Here's an example:
<!-- Converts the Status attribute text to a SolidColorBrush used to draw
the output of statusDisplayNameGroup. -->
<local:ValueConverterGroup x:Key="statusForegroundGroup">
<local:IntegerStringToProcessingStateConverter />
<local:ProcessingStateToColorConverter />
<local:ColorToSolidColorBrushConverter />
</local:ValueConverterGroup>
Great stuff. Thanks, Josh. :)
Solution 3
Town's implementation of Gareth Evans's Silverlight project is great, however it does not support different converter parameters.
I modified it so you can provide parameters, comma delimited (unless you escape them of course).
Converter:
public class ValueConverterGroup : List<IValueConverter>, IValueConverter
{
private string[] _parameters;
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if(parameter != null)
_parameters = Regex.Split(parameter.ToString(), @"(?<!\\),");
return (this).Aggregate(value, (current, converter) => converter.Convert(current, targetType, GetParameter(converter), culture));
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
private string GetParameter(IValueConverter converter)
{
if (_parameters == null)
return null;
var index = IndexOf(converter as IValueConverter);
string parameter;
try
{
parameter = _parameters[index];
}
catch (IndexOutOfRangeException ex)
{
parameter = null;
}
if (parameter != null)
parameter = Regex.Unescape(parameter);
return parameter;
}
}
Note: ConvertBack is not implemented here, see my Gist for the full version.
Implementation:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:converters="clr-namespace:ATXF.Converters;assembly=ATXF" x:Class="ATXF.TestPage">
<ResourceDictionary>
<converters:ValueConverterGroup x:Key="converters">
<converters:ConverterOne />
<converters:ConverterTwo />
</converters:ValueConverterGroup>
</ResourceDictionary>
<Label Text="{Binding InitialValue, Converter={StaticResource converters}, ConverterParameter='Parameter1,Parameter2'}" />
</ContentPage>
Solution 4
Yes, there are ways to chain converters but it does not look pretty and you don't need it here. If you ever come to need this, ask yourself is that really the way to go? Simple always works better even if you have to write your own converter.
In your particular case, all you need to do is format a converted value to a string. StringFormat
property on a Binding
is your friend here.
<TextBlock Text="{Binding Value,Converter={StaticResource myConverter},StringFormat=D}" />
Solution 5
Here is a small extension of Town's answer to support multi-binding:
public class ValueConverterGroup : List<IValueConverter>, IValueConverter, IMultiValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return this.Aggregate(value, (current, converter) => converter.Convert(current, targetType, parameter, culture));
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return Convert(values as object, targetType, parameter, culture);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
Mal Ross
UX researcher / designer. Previously a C++ / C# software developer, working on Windows desktop apps, with a keen interest in usability.
Updated on September 20, 2020Comments
-
Mal Ross almost 4 years
I've got a situation in which I need to show an integer value, bound to a property on my data context, after putting it through two separate conversions:
- Reverse the value within a range (e.g. range is 1 to 100; value in datacontext is 90; user sees value of 10)
- convert the number to a string
I realise I could do both steps by creating my own converter (that implements IValueConverter). However, I've already got a separate value converter that does just the first step, and the second step is covered by Int32Converter.
Is there a way I can chain these two existing classes in XAML without having to create a further class that aggregates them?
If I need to clarify any of this, please let me know. :)
Thanks.
-
Yaakov Shoham over 11 yearsIn this solution, each converter must deal with one type only (it must be declared in the single-ValueConversion-attribute). @Town solution can cope with multiconverters too.
-
Jacek Gorgoń over 10 yearsIf you use bindings heavily, writing custom converter to chain converters ends up with tons of dumb converters for all sorts of configurations. In that case the accepted answer is a wonderful solution.
-
Nick Udell about 10 yearsIs it best, for an implementation of ConvertBack to make a copy of the collection and reverse it, and then Aggregate over that? So the ConvertBack would be
return this.Reverse<IValueConverter>().Aggregate(value, (current, converter) => converter.ConvertBack(current, targetType, parameter, culture));
-
Jake Berger over 9 yearsplease post the implementation; otherwise, linkrot
-
Aleksandar Toplek almost 9 years@DLeh This is not really elegant as is doesn't work. It provides all converters with final target type instead of correct target type...
-
LightMonk over 5 yearsHow can I use this with a MultiValueConverter as first Converter?
-
Mal Ross almost 5 years@Town A colleague just found this question and it made me look it up again, for nostalgia's sake. Only, I just noticed you weren't getting the credit you deserved (I'd accepted my own answer!), so I've now marked your answer as accepted. Only about 9 years late... :facepalm:
-
Town almost 5 years@MalRoss Haha! Thank you! Good to hear it's still useful, I haven't touched Silverlight now for about 8 of those years and yet this is still my most popular answer :)
-
Katjoek about 4 yearsDownside of this implementation is that the target type must be the same for all the converters. I suggest looking at Mal Ross' answer.