| name | wpf-rule-converter-patterns |
| description | WPF IValueConverter rules: MarkupExtension singleton, pure functions, null/UnsetValue handling, TemplateBinding. |
| user-invocable | false |
Converter Patterns
Standards for implementing IValueConverter in wpf-dev-pack projects.
MarkupExtension Singleton Pattern
Every converter is a MarkupExtension so it can be used directly in XAML without
declaring a resource, and ProvideValue returns a single shared instance
(converters are stateless, so a shared instance is safe and avoids
ResourceDictionary clutter). This is the canonical converter pattern,
matching the /wpf-dev-pack:make-wpf-converter scaffolder and the
using-converter-markup-extension knowledge topic. Pick this one pattern — do
NOT also expose a separate static Instance property.
Derive from a small base class (the scaffolder generates it once per project):
namespace MyApp.Converters;
public abstract class ConverterMarkupExtension<T> : MarkupExtension, IValueConverter
where T : class, new()
{
private Lazy<T> _converter = (() => T());
=> _converter.Value;
? Convert(? , Type targetType, ? parameter, CultureInfo culture);
? ConvertBack(? , Type targetType, ? parameter, CultureInfo culture)
=> NotSupportedException();
}
: <>
{
? Convert(? , Type targetType, ? parameter, CultureInfo culture)
{
( || == DependencyProperty.UnsetValue)
Visibility.Collapsed;
invert = parameter ;
( b && (b ^ invert)) ? Visibility.Visible : Visibility.Collapsed;
}
}