Search code examples
c#wpfmarkup-extensions

MarkupExtension, IValueConverter Defaul Constructor


I'm confused why I need the default constructor in this use case.

<Button Name="RemoveWord" IsEnabled="{Binding SearchText.Length, Converter={aw:CountToBoolConverter CountToBoolConverter}, ElementName=WordForAction }" />

and my converter is

public class CountToBoolConverter : MarkupExtension,  IValueConverter
{
    public CountToBoolConverter(string value)
    {

    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool enabled = (int)value > 0;
        return enabled;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}

What is the default constructor used for in this case and how do I know what parameters it expects?


Solution

  • Your MarkupExtension needs a constructor with string parameter (which is not a default constructor) because you added an unnecessary string to the XAML expression that creates the converter:

    Converter={aw:CountToBoolConverter CountToBoolConverter}
    

    The second CountToBoolConverter string here is pointless and the expression should just be

    Converter={aw:CountToBoolConverter}