Reputation: 66
In a Resource Dictionary I have stored a ViewBox with a Canvas
<Style x:Key="MyPathStyle" TargetType="Path">
<Setter Property="Fill" Value="{Binding BackgroundColorBrush,
RelativeSource={RelativeSource AncestorType=iconcontrols:IconAsVisualBrush}}"/>
</Style>
<Viewbox x:Key="Icon2">
<Canvas Width="40.000" Height="40.000">
<Canvas>
<Path Fill="#ff99baf4" Data="F1 M 14.377,23.798" />
<Path Style="{StaticResource MyPathStyle}" Data="..." />
</Canvas>
</Canvas>
</Viewbox>
So I want to change the color of the second Path using the BackgroundColorBrush of my control Container (called IconAsVisualBrush ). It is
<Grid x:Name="GridIconBrush" Width="40" Height="40">
<Grid.Background>
<VisualBrush x:Name="CtrlVisualBrush" Stretch="Uniform" />
</Grid.Background>
</Grid>
The VisualBrush is set in cs:
private static void OnIconBrushResourceChanged(DependencyObject source
, DependencyPropertyChangedEventArgs e)
{
IconAsVisualBrush control = source as IconAsVisualBrush;
control.CtrlVisualBrush.Visual = (Viewbox)Application.Current.FindResource(e.NewValue);
}
In my UserControl I can draw the ViewBox with the folliwing xaml:
<iconcontrols:IconAsVisualBrush BackgroundColorBrush="White"
IconBrushResource="Icon2"/>
<iconcontrols:IconAsVisualBrush BackgroundColorBrush="Red"
IconBrushResource="Icon2"/>
The canvas is correctly drawn but not the color. I receive: Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='IconAsVisualBrush', AncestorLevel='1''. BindingExpression:Path=BackgroundColorBrush; DataItem=null; target element is 'Path' (Name=''); target property is 'Fill' (type 'Brush')
Is there a way to change only the Path Fill color set inside a owner Control (not a dynamic resource that make all IconAsVisualBrush with the same color) so that I can draw the same shape with different fill colors?
Upvotes: 0
Views: 3759
Reputation: 432
Your issue is that the Setter in your Style is unable to find the IconAsVisualBrush, presumably because it is not part of the Path's visual tree. Have you considered using triggers? It's difficult to suggest a solution without knowing your application architecture and what is calling OnIconBrushResourceChanged - however since we're talking about WPF, I'll make an educated guess that you are using MVVM. If so, you could use DataTriggers like so:
<Style x:Key="MyPathStyle" TargetType="Path">
<Setter Property="Fill" Value="White" />
<Style.Triggers>
<DataTrigger Binding="{MyColourChangedProperty}"
Value="True">
<DataTrigger.Setters>
<Setter Property="Fill" Value="Red"/>
</DataTrigger.Setters>
</DataTrigger>
</Style.Triggers>
</Style>
EDIT: To clarify, the style I've suggested here will give you a default fill of white, but if you set 'MyColourChangedProperty' (or whatever you bind to) to true, it will turn red.
Upvotes: 1