A rating control in XAML
For a pet project I've been working on in WPF I needed a control that would let the user provide a rating between 0 and 5, for example like the one in iTunes and on numerous web sites:
After googling a bit I found some samples, including this one posted by Zhou Yong on msdn forums.
However, there was some issues with the functionality (how it reacts to clicks when you click a star that is already lit) and the visuals (the starts themselves and some other minor issues relating to sizing and scaling) so I decided to touch it up a bit. The end result looks like this:
It (like the original) is based on toggle buttons with a new template to redo the visuals. It quite nicely illustrates the power of templates in WPF, and what can be achieved just with a little bit of code in a user control. The template looks like this:
1: <ControlTemplate x:Key="starTemplate" TargetType="{x:Type ToggleButton}">
2: <Viewbox>
3: <Path Name="star" Fill="Gray" Data="F1 M 145.637,174.227L 127.619,110.39L 180.809,70.7577L 114.528,68.1664L 93.2725,5.33333L 70.3262,67.569L 4,68.3681L 56.0988,109.423L 36.3629,172.75L 91.508,135.888L 145.637,174.227 Z"/>
4: </Viewbox>
5: <ControlTemplate.Triggers>
6: <Trigger Property="IsChecked" Value="True">
7: <Setter TargetName="star" Property="Fill" Value="White"/>
8: </Trigger>
9: </ControlTemplate.Triggers>
10: </ControlTemplate>
When working on this I realized how hard it is to find coordinates for a star. The ones I ended up using were lifted from a blog post by Jaime Rodriguez. They are a little bit crooked, but they were the best I could find.
Of course the whole control should ideally be implemented as a custom control so that it properly supports styles and templating, but I'll leave that exercise for later.
The code for this sample can be downloaded from here.