Reputation: 3663
I created a WPF custom control, which works fine. It has a style which sets some properties and a template.
Now i want to change the control, so it has a 'Active' property. If this is true it should use the Property 'ActiveBrush' for the Stroke of some Rectangles in the Template, else it should use 'InactiveBrush'.
I want to use the ActiveBrush as the default Stroke, and change it to InactiveBrush with a Trigger.
This works fine with one Rectangle when i use this:
<Trigger Property="Active" Value="False">
<Setter TargetName="Rec1" Property="Stroke" Value="{Binding Path=InactiveBrush, RelativeSource={RelativeSource TemplatedParent}}"/>
</Trigger>
But since I don't want to set each rectangle with a seperated setter, I am asking myself if it shouldn't be possible to set the property of all Rectangles in the Template with one Setter.
I already tried:
<Trigger Property="Active" Value="False">
<Setter Property="Rectangle.Stroke" Value="{Binding Path=InactiveBrush, RelativeSource={RelativeSource TemplatedParent}}"/>
</Trigger>
But this didn't work.
Has anyone a suggestion, how to implement this?
Thanks in advance.
Upvotes: 0
Views: 230
Reputation: 6289
@Robert Rossney - this style will not run since a target type of Rectangle doesn't have a property Active. But that is the right path to go, with a minor change:
<Style TargetType="Rectangle">
<Style.Triggers>
<DataTrigger Binding="{Binding Active, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MyControl}}}" Value="False">
<Setter Property="Stroke" Value="{Binding Path=InactiveBrush, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MyControl}}}"/>
</DataTrigger>
</Style.Triggers>
</Style>
This style should be nested in Style.Resources of the control style or in ControlTemplate.Resources of the ControlTemplate for the control. This way you're localizing this style only to your control. Any Rectangle outside of your control will not be affected.
Upvotes: 1
Reputation: 96722
I'm sure you know this but are just overlooking it: If you want to apply a style to all controls of a type, create a style with a TargetType
of that type and put it in your custom control's resource dictionary. If you still need to apply specific styles to individual controls of that type, define those styles using the BasedOn
property.
So, in your MyControl.Resources
element, you'd put:
<Style TargetType="Rectangle">
<Style.Triggers>
<Trigger Property="Active" Value="False">
<Setter Property="Stroke" Value="{Binding Path=InactiveBrush, RelativeSource={RelativeSource TemplatedParent}}"/>
</Trigger>
<Style>
<Style>
and any Rectangle
that needed its own style would start like this:
<Style TargetType="Rectangle" BasedOn="{StaticResource {x:Type Rectangle}}">
Upvotes: 1