Binding a color resource?

I have a strange problem that made me stop. I am modifying the WPF calendar management template, and for the reasons I explain below, for my text color I should use the Color resource, not the SolidColorBrush resource. Right now my Color resource is as follows:

 <!-- My Colors --> <Color x:Key="MyTextColor">Blue</Color> 

Now I want to bind the Color resource to the parent property, but the Color object does not have the Binding property. So how can I link this resource? Thank you for your help.


Note why I should use the Color resource: The WPF calendar control animates its text for the mouse in several places, and each animation uses the name SolidColorBrush . I can’t replace the brushes with a resource link, because I want to save the animation, which means that I have to save the name. But I can replace the colors of the brush, as in this brush named TextColor:

 <!-- Modification: Changed template brush color --> <SolidColorBrush x:Name="TextColor"> <SolidColorBrush.Color> <StaticResource ResourceKey="MyTextColor" /> </SolidColorBrush.Color> </SolidColorBrush> 
+4
source share
2 answers

We had the same problem in our software, and she came up with this solution. Basically, you create a class that implements an extension for the WPF static resource class that handles the binding and then consumes it according to your XAML code. Pretty easy to use.

0
source

I chose smoura's answer as correct because it answers the question I asked. However, I think I might have asked the wrong question, and there is a better solution to the problem.

I decided that I didn’t manage to use the resource, and then I tried to connect this resource. A much better approach is to simply bind the Color property directly. To do this, I created a simple IValueConverter called BrushToColorConverter , and then used this to associate the named brush color with the Foreground property of the Foreground created. The markup is as follows:

 <!-- Modification: Changed template brush color --> <SolidColorBrush x:Name="TextColor" Color="{Binding Path=Foreground, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Converter={StaticResource BrushToColorConverter}}" /> 

This approach completely excludes the Color resource that I used earlier. This is simpler and, I suspect, more efficient.

+5
source

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


All Articles