tags:

views:

63

answers:

4

Is there a way to use a ValueConverter without defining it in a resource? As is the syntax is pretty verbose.

A: 

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.

Anero
+3  A: 

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

aqwert
+1 for teaching me a new technique, but I think the thing I care most about is making the binding declaration shorter. I'm seriously thinking about dumping converters entirely and switching back to PyBinding.
Jonathan Allen
A: 

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}"
Jay
Ideally we would only have to write Converter="NegatingConverter", everything else is line noise needed to make the compiler happy.
Jonathan Allen
+4  A: 

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.

Daniel
+1 you beat me by 10 seconds :) Here is another link... http://drwpf.com/blog/2009/03/17/tips-and-tricks-making-value-converters-more-accessible-in-markup/
IanR
You win the prize sir.
Jonathan Allen