Every time I am writing a value converter I'm wondering how to handle the targetType
parameter specified at the Convert
and ConvertBack
method of the IValueConverter :
object Convert(object value, Type targetType, object parameter, CultureInfo culture)
object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
I noticed that many implementations are using the targetType
simply by checking it ( if (targetType == typeof(RequiredType))
) and throwing some exceptions or returning a null value if the type is not like expected:
But also many of them (I think it's the majority) are totally ignoring the parameter:
I tried to find some guidlines or tips using the parameter but unfortunately I found absolutely nothing. Both approaches are doing their jobs, but is one of the approaches more correct? What are the pros and cons of the approaches? Should I ignore or use the parameter?
My personal view is not to check the parameter to allow the usage of the converter more flexible but I'm excited to get your opinions.
The caller will be telling you what is the desired type to convert the value:
true/false
to Visibility
, then you can just ignore the targetType
. It's obvious how to use the converter, there is no need for trowing exceptions. targetType
, eg using the converter to convert to ImageSource
or Brush
. In the first case you want to generate an image (eg error image), in the other you want a simple color (eg red). targetType
you don't want to and it's not obvious if it's supported or not, then you can warn the developer by throwing an exception. I think most common scenario is the 1).
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.