Question

Simple question:

Why do I have to have a constructor for a IValueConverter?

I'm not asking, why do I have to have an empty constructor, I'm asking why do I have to have one at all?

If I have:

public class PauseButtonValueConverter : MarkupExtension, IValueConverter
{
  //public PauseButtonValueConverter() //<- Uncomment this and the error is fixed
  //{
  //}

  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    throw new NotImplementedException();
  }

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

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

Then, my VS2012 gives me the compile-time error: No constructor for type 'PauseButtonValueConverter' has 0 parameters.

If I add the constructor, the error is fixed.

Was it helpful?

Solution

It's because you're deriving from MarkupExtension, the constructor for which is protected. In this case, the compiler doesn't auto-generate a default constructor. You must add it yourself.

In most cases, you shouldn't need to derive from MarkupExtension when creating a value converter. I'm assuming you have a reason for this, but if not, just remove the base class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top