Is there a way to use a ValueConverter without defining it in a resource? As is the syntax is pretty verbose.
You could create an attach property to hook up to the binding and perform the conversion, though if the only reason is for breverity, I wouldn't recommend adding an extra piece of complexity to your code.
Within your converter you can have a static property or field that you can refer to in xaml. No need for adding a resource.
public class MyConverter : IValueConverter
{
public static readonly MyConverter Instance = new MyConverter();
... }
And in XAML
<TextBlock Text="{Binding Path=., Converter={x:Static l:MyConverter.Instance}}" />
Beaware that these converters should not store any state as the same instance will be used. If you are iffy about public fields just create a static property instead.
Though it is debatable that this is better
How exactly are you declaring these converters such that verbosity is an issue?
<conv:NegatingConverter x:Key="NegatingConverter" />
One line per converter per application.
Usage isn't verbose either.
Converter="{StaticResource NegatingConverter}"
You can use a MarkupExtension to minimise the amount of xaml code required. E.g:
public class MyConverter: MarkupExtension, IValueConverter
{ private static MyConverter _converter;
public object Convert(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
// convert and return something
}
public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
// convert and return something (if needed)
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (_converter == null)
_converter = new MyConverter();
return _converter;
}
}
You end up with a syntax like this:
{Binding Converter={conv:MyConverter}}
This approach has an added advantage of ensuring that all your converters are singletons.
This article does a great job of explaining the concept and provides sample code.