1. 创建IValueConverter
的转换器类,该类实现随机生成颜色
public class RandomColorConverter : IValueConverter
{
private Random random = new Random();
private byte[] randomColors = new byte[3];
private Dictionary<int, SolidColorBrush> groupColer = new Dictionary<int, SolidColorBrush>();
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Image image = value as Image;
if (image != null)
{
int id = image.FilePath.GroupID;
if (!groupColer.Keys.Contains(id))
{
if (id == 0)
{
randomColors[0] = (byte)0;
randomColors[1] = (byte)0;
randomColors[2] = (byte)0;
}
else
{
randomColors[0] = (byte)random.Next(0, 256); // Red
randomColors[1] = (byte)random.Next(0, 256); // Green
randomColors[2] = (byte)random.Next(0, 256); // Blue
}
groupColer[id] = new SolidColorBrush(Color.FromRgb(randomColors[0], randomColors[1], randomColors[2]));
}
return groupColer[id];
}
return new SolidColorBrush(Color.FromRgb(0, 0, 0));
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
2. 在你的XAML资源中注册这个转换器
<UserControl.Resources>
<ResourceDictionary>
<converters:RandomColorConverter x:Key="RandomColorConverter"/>
</ResourceDictionary>
</UserControl.Resources>
3. 绑定属性
Foreground="{Binding Converter={StaticResource RandomColorConverter}}"