Binding a Color Resource?
I have an odd problem that's got me stumped. I am modifying the WPF Calendar control template, and for reasons that I explain below, I have to use a Color
resource, rather than a SolidColorBrush
resource, for my text color. Right now, my Color
resource looks like this:
<!-- My Colors -->
<Color x:Key="MyTextColor">Blue<开发者_StackOverflow中文版/Color>
Now I want to bind the Color
resource to a parent property, but the Color
object doesn't have a Binding
property. So, how would I go about binding this resource? Thanks for your help.
Note on why I have to use a Color resource: The WPF Calendar control animates its text for mouse-overs in several places, and each animation uses a named SolidColorBrush
. I can't replace the brushes with a resource reference, since I want to preserve the animations, which means I have to preserve the name. But I can replace the brush colors, as I did in this brush named TextColor:
<!-- Modification: Changed template brush color -->
<SolidColorBrush x:Name="TextColor">
<SolidColorBrush.Color>
<StaticResource ResourceKey="MyTextColor" />
</SolidColorBrush.Color>
</SolidColorBrush>
I have selected smoura's answer as being the correct one, because it does answer the question that I had asked. However, I think I may have asked the wrong question, and therein lies a better solution to the problem.
I decided I was off course in using a resource, and then trying to bind that resource. A much better approach is to simply bind the Color
property directly. To do that, I created a simple IValueConverter
called BrushToColorConverter
, then used that to bind the named brush's color to the Foreground
property of the UserControl
that I am creating. The markup looks like this:
<!-- 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 eliminates the Color
resource that I had used previously. It is simpler and, I suspect, more efficient.
We had the same problem in our software and came up with this solution. Basically you create a class that implements an extension to the static resource class of WPF which handles binding and then consume it on your XAML code. Pretty easy to use.
精彩评论