Reputation: 2859
I have a wpf Window
that is using a ResourceDictionary
that has a SolidColorBrush
defined in it.
I can choose what color to set the SolidColorBrush
as with it's Color property, by using the hex values like so:
<SolidColorBrush Color="#FF0000"/>
When I try to set it like this:
<SolidColorBrush Color="{Binding UserSelectedColor}"/>
It will obviously not work because a ResourceDictionary
does not have a DataContext
to set.
I tried to do this because I thought that maybe the Binding would use whatever DataContext
is set on the Control
that is using the SolidColorBrush
, but that doesn't seem to be working.
So I'm wondering how am I supposed to get the Color
from the ViewModel
if I can't set the DataContext
of the ResourceDictionary
Upvotes: 1
Views: 4436
Reputation: 128136
A possible solution would be to also put the ViewModel object into the ResourceDictionary and explicitly set the Source
of the binding:
<Window ...>
<Window.Resources>
<local:ViewModel x:Key="ViewModel"/>
<SolidColorBrush x:Key="UserSelectedBrush"
Color="{Binding UserSelectedColor, Source={StaticResource ViewModel}}"/>
</Window.Resources>
<Grid DataContext="{StaticResource ViewModel}">
<Rectangle Fill="{StaticResource UserSelectedBrush}"/>
</Grid>
</Window>
It would however be easier to declare a UserSelectedBrush
property of type Brush
in the ViewModel and directly bind to that property:
<Rectangle Fill="{Binding UserSelectedBrush}"/>
Upvotes: 4