Last active
June 11, 2024 19:32
-
-
Save awatertrevi/68924981bdea1800f5af162e4eb2b1f5 to your computer and use it in GitHub Desktop.
ValueConverterGroup with parameters.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ValueConverterGroup : List<IValueConverter>, IValueConverter | |
{ | |
private string[] _parameters; | |
private bool _shouldReverse = false; | |
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) | |
{ | |
ExtractParameters(parameter); | |
if (_shouldReverse) | |
{ | |
Reverse(); | |
_shouldReverse = false; | |
} | |
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) | |
{ | |
ExtractParameters(parameter); | |
Reverse(); | |
_shouldReverse = true; | |
return this.Aggregate(value, (current, converter) => converter.ConvertBack(current, targetType, GetParameter(converter), culture)); | |
} | |
private void ExtractParameters(object parameter) | |
{ | |
if (parameter != null) | |
_parameters = Regex.Split(parameter.ToString(), @"(?<!\\),"); | |
} | |
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's it with @ADIX7's suggested edit and other refactorings
This is how I used it