While on a recent project, I was tasked with creating an element that displays a rectangle whose width is equal to a percentage and a label that describes the percentage. Also, if the percentage is within certain ranges, the color is different. In this case, there are three ranges.
| Range |
Color |
Description |
| 0 – 74 |
red |
low |
| 75 – 84 |
yellow |
medium |
| 85 – 100 |
green |
high |
Creating the rectangle and label in XAML is easy, as is setting the width and description with bindings.
<Rectangle x:Name="bar" Width="{Binding Percentage}"/> <TextBlock x:Name="label" Text="{Binding Description}"/>
The interesting part of the task is how best to set its color. Six lines of code come immediately to mind.
if(percentage < 75) bar.Fill= Brushes.Red; else if(percentage < 85) bar.Fill= Brushes.Yellow; else bar.Fill= Brushes.Green;
The difficulty here is not in creating this code (which takes less than a minute to type) but in placing and invoking it. One possibility is to create a Rectangle.SizeChanged event handler for the bar object and put this code in it. It's straightforward and is easy to package in a user control.
I don't like it. My WPF mantra is "don't write code". Plus, I already wrote almost the same code to determine the Description property. Here's another way to accomplish the same result but without any procedural code.
Somewhere in the Resources section, add this.
<Style x:Key="PercentageStyle" TargetType="{x:Type Rectangle}"> <Setter Property="Fill" Value="Green"/> <Style.Triggers> <DataTrigger Binding="{Binding Description}" Value="Low"> <Setter Property="Fill" Value="Red"/> </DataTrigger> <DataTrigger Binding="{Binding Description}" Value="Medium"> <Setter Property="Fill" Value="Yellow"/> </DataTrigger> </Style.Triggers> </Style>
Then, use this style in the bar element, like so.
<Rectangle x:Name="bar" Width="{Binding Percentage}" Style="{StaticResource PercentageStyle}"/>
Without addressing the obvious localization issues, I managed to leverage the range discrimination code by binding to the Description property.