WPF: How to register additional implicit value converters?

I asked a question about how to avoid adding custom value converters to one application resource:

Using value converters in WPF without having to define them as resources in the first place

However, I would like to go one step further than this and register the converters, which are then implicit, as in this example:

<SolidColorBrush Color="Blue" /> 

Here, I assume that some implicit "StringToSolidColorBrushConverter" is starting, which makes this 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 because the WPC cannot just pick and use, there is no implcit ColorToSolidColorBrushConverter . I know how to create it, but how would I “register” it so that WPF automatically uses it without specifying a converter in the binding expression?

+6
source share
1 answer

If you look at the source code, you will find it

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

The conversion is done using the ColorConverter.

And

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

If the conversion is done using BrushConverter.

There is no “implicit” conversion that you can register. All this is done by applying TypeConverter attributes with the type of the corresponding value converter to the corresponding 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> 
+4
source

Source: https://habr.com/ru/post/913441/


All Articles