你可以创建一个IValueConverter
改变矩形的颜色
这是一个非常快速(粗略)的示例:
Xaml:
<Grid Background="DarkBlue" >
<Grid.Resources>
<local:RatingConverter x:Key="RatingConverter" OnBrush="#FFFFFFFF" OffBrush="#50FFFFFF" />
<Style TargetType="Rectangle">
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="VerticalAlignment" Value="Bottom" />
<Setter Property="Margin" Value="5,0,0,0" />
</Style>
</Grid.Resources>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<Rectangle Width="5" Height="5" Fill="{Binding RatingValue, Converter={StaticResource RatingConverter}, ConverterParameter=1}"/>
<Rectangle Width="5" Height="10" Fill="{Binding RatingValue, Converter={StaticResource RatingConverter}, ConverterParameter=2}"/>
<Rectangle Width="5" Height="15" Fill="{Binding RatingValue, Converter={StaticResource RatingConverter}, ConverterParameter=3}"/>
<Rectangle Width="5" Height="20" Fill="{Binding RatingValue, Converter={StaticResource RatingConverter}, ConverterParameter=4}"/>
<Rectangle Width="5" Height="25" Fill="{Binding RatingValue, Converter={StaticResource RatingConverter}, ConverterParameter=5}"/>
</StackPanel>
</Grid>
Code:
namespace WpfApplication14
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
DataContext = this;
}
public int RatingValue
{
get { return (int)GetValue(RatingValueProperty); }
set { SetValue(RatingValueProperty, value); }
}
// Using a DependencyProperty as the backing store for RatingValue. This enables animation, styling, binding, etc...
public static readonly DependencyProperty RatingValueProperty =
DependencyProperty.Register("RatingValue", typeof(int), typeof(UserControl1), new UIPropertyMetadata(0));
}
public class RatingConverter : IValueConverter
{
public Brush OnBrush { get; set; }
public Brush OffBrush { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int rating = 0;
int number = 0;
if (int.TryParse(value.ToString(), out rating) && int.TryParse(parameter.ToString(), out number))
{
if (rating >= number)
{
return OnBrush;
}
return OffBrush;
}
return Brushes.Transparent;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
Usage:
<Window x:Class="WpfApplication14.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:WpfApplication14"
Title="MainWindow" Height="350" Width="525">
<Grid>
<l:UserControl1 RatingValue="3" />
</Grid>
</Window>
Result: