Reputation: 1134
I'm afraid I don't have the code available here to paste, but I'd appreciate some guidance on best practices.
I currently have a polygon defined in my XAML file in Visual Studio 2010, C#, .NET 4.0. The polygon is defined with a fixed color; however, depending on the value of the binding, the color can change using a trigger.
// non-working code - trying to avoid
<Polygon ... Fill="Red" />
<Grid.Triggers>
<Trigger ...>
<Setter Property="..." Value="Yellow" />
</Trigger>
<Trigger ...>
<Setter Property="..." Value="Green" />
</Trigger>
<Trigger ...>
<Setter Property="..." Value="Blue" />
</Trigger>
</Grid.Triggers>
Now, I need to break up the polygon into several pieces that are joined together to look like one complete shape. I have broken up the polygon into two polygons and a rectangle.
What is the best way to change colors as before such that I don't repeat code?
I don't want a trigger mapping four different enum values to four different colors, and then for each color, defining the same three shapes to be colored.
// non-working code - trying to avoid
<Polygon ... Fill="Red" />
<Polygon ... Fill="Red" />
<Rectangle ... Fill="Red" />
<Grid.Triggers>
<Trigger ...>
<Setter Property="..." Value="Yellow" />
<Setter Property="..." Value="Yellow" />
<Setter Property="..." Value="Yellow" />
</Trigger>
<Trigger ...>
<Setter Property="..." Value="Green" />
<Setter Property="..." Value="Green" />
<Setter Property="..." Value="Green" />
</Trigger>
<Trigger ...>
<Setter Property="..." Value="Blue" />
<Setter Property="..." Value="Blue" />
<Setter Property="..." Value="Blue" />
</Trigger>
</Grid.Triggers>
Is there a way I can define a color as a static resource and use that resource to color my three shapes, and then use the trigger to toggle the R/G/B values of the resource?
// non-working code - trying to do
<SolidColorBrush x:Key="MyBrush" Color="Red"/>
<Polygon ... Fill="{StaticResource MyBrush}" />
<Polygon ... Fill="{StaticResource MyBrush}" />
<Rectangle ... Fill="{StaticResource MyBrush}" />
<Grid.Triggers>
<Trigger ...>
<Setter Property="..." Value="Yellow" />
</Trigger>
<Trigger ...>
<Setter Property="..." Value="Green" />
</Trigger>
<Trigger ...>
<Setter Property="..." Value="Blue" />
</Trigger>
</Grid.Triggers>
Thanks.
Upvotes: 0
Views: 121
Reputation: 8791
Best way is called using Binding with Converter instead of having tons of triggers listening to different states. :)
Here is code:
<Window.Resources>
<local:BelowZeroConverter x:Key="converter"/>
</Window.Resources>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Value, Converter={StaticResource converter}}" Value="1">
<Setter Property="Foreground" Value="Black"></Setter>
</DataTrigger>
Upvotes: 1