I was trying to chain converters as Town's answer in Is there a way to chain multiple value converters in XAML??
I like to make individual converters more strict by having targetType check as well :-
if (targetType != typeof(bool))
throw new InvalidOperationException("The target must be a
boolean");
But the chain fails as the end target type is different from the target at each stage.
I can remove the type check to make less strict as given in most of examples on SO, but I would prefer a chaining which respects each converter's type check as well. E.g. for better unit testing etc.
Also the interface IValueConverter doesn't expose the target type, I find it difficult to add that check myself.
public class InverseBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (targetType != typeof(bool))
throw new InvalidOperationException("The target must be a boolean");
if (!(value is bool))
throw new ArgumentException("Argument 'value' must be of type bool");
return !(bool)value;
}
....
}
[ValueConversion(typeof(bool), typeof(Visibility))]
public class VisibilityFromBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (targetType != typeof(Visibility))
throw new InvalidOperationException("The target must be a Visibility");
if (!(value is bool))
throw new ArgumentException("Argument 'value' must be of type bool");
var isVisible = (bool)value;
return isVisible ? Visibility.Visible : Visibility.Collapsed;
}
....
}
And the composite is like :-
<Converters:ValueConverterGroup x:Key="InvertAndVisible">
<Converters:InverseBooleanConverter />
<Converters:VisibilityFromBoolConverter />
</Converters:ValueConverterGroup>
But I get exception "The target must be a boolean" from InverseBooleanConverter as it expects target to be bool instead of Visibility (the end target of chain).