Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: How do I register additional implicit value converters?

I found a question asking about ways to avoid adding custom value converters to one's application resources:

Using Value Converters in WPF without having to define them as resources first

However I'd like to go one step beyond that and register converters that are then implicit, as in this example:

<SolidColorBrush Color="Blue" />

Here, I am assuming that some implicit "StringToSolidColorBrushConverter" is kicking-in that makes the example work.

This example does not work:

<Window.Resources>
    <Color x:Key="ForegroundFontColor">Blue</Color>
</Window.Resources>

<TextBlock Foreground={StaticResource ForegroundFontColor}>Hello</TextBlock>

I believe that's because there is no implcit ColorToSolidColorBrushConverter that WPF can just pick up and use. I know how to create one, but how would I "register" it so that WPF uses it automagically without specifying the converter in the binding expression at all?

like image 340
Neil Barnwell Avatar asked Apr 17 '12 16:04

Neil Barnwell


People also ask

What is IValueConverter in Xamarin forms?

Data namespace, but this IValueConverter is in the Xamarin. Forms namespace.) Classes that implement IValueConverter are called value converters, but they are also often referred to as binding converters or binding value converters.

What is a value converter?

A Value Converter is any class which implements the IMvxValueConverter interface. The IMvxValueConverter interface provides: a Convert method - for changing ViewModel values into View values. a ConvertBack method - for changing View values into ViewModel values.


1 Answers

If you look at the source code you'll find this

public sealed class SolidColorBrush : Brush
{
  public Color Color
  { ... }
  ...
}

[TypeConverter(typeof (ColorConverter))]
public struct Color : IFormattable, IEquatable<Color>
{
    ...
}

The conversion is done by the ColorConverter.

And also

[TypeConverter(typeof (BrushConverter))]
public abstract class Brush : Animatable, IFormattable, DUCE.IResource
{ ... }

public class TextBlock : ...
{  
   public Brush Foreground
   { ... }
}

Where the conversion is done by BrushConverter.

There's no 'implicit' conversion that you can register. It's all done by applying TypeConverter attributes with the type of the appropriate value converter to relevant properties or classes.

In your example you need to use

<Window.Resources>
    <SolidColorBrush x:Key="ForegroundFontColor" Color="Blue"/>
</Window.Resources>

<TextBlock Foreground={StaticResource ForegroundFontColor}>Hello</TextBlock>
like image 69
Phil Avatar answered Sep 21 '22 22:09

Phil