简体   繁体   中英

.net WPF IValueConverter Constructor

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM