我想在列表框中生成不同颜色的项目。例如 - 每个项目都有不同颜色的矩形。我做不到。 到目前为止我已经创建了一个这样的类
public class RandomColorGenerator
{
public Color randomBrush { get; set; }
private static Random randomColor = new Random();
private static uint[] uintColors =
{
0xFF34AADC,0xFFFF2D55,0xFF007AFF,0xFFFF9500,0xFF4CD964,
0xFFFFCC00,0xFF5856D6,0xFFFF3B30,0xFFFF4981,0xFFFF3A2D
};
public RandomColorGenerator()
{
randomBrush = generateRandomColor();
}
private static Color ConvertColor(uint uintCol)
{
byte A = (byte)((uintCol & 0xFF000000) >> 24);
byte R = (byte)((uintCol & 0x00FF0000) >> 16);
byte G = (byte)((uintCol & 0x0000FF00) >> 8);
byte B = (byte)((uintCol & 0x000000FF) >> 0);
return Color.FromArgb(A, R, G, B); ;
}
public static Color generateRandomColor()
{
return ConvertColor(uintColors[randomColor.Next(0, 9)]);
}
}
以及在 XAML 中
<ListBox x:Name="TestListBox" >
<ListBox.ItemTemplate>
<DataTemplate>
<Rectangle Margin="10" Height="100" Width="400" >
<Rectangle.Fill>
<SolidColorBrush Color="{Binding randomBrush,
Source={StaticResource colorgenerate}}">
</SolidColorBrush>
</Rectangle.Fill>
</Rectangle>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
完成所有这些后,我得到这样的结果 -
重新启动应用程序后,我得到了这个
虽然每当我运行应用程序时我都会得到随机颜色。但一种颜色应用于所有矩形。
我不知道如何获得想要的结果。 我想要这样的东西 -
如有任何帮助,我们将不胜感激。
最佳答案
重点是,仅当您创建 RandomColorGenerator 类时才生成 RabdomBrush。
每次调用时都应该生成新的 RandomBrush。有点像这样:
public class RandomColorGenerator
{
public Color randomBrush {
get {return generateRandomColor(); }
}
....
关于c# - 将随机颜色绑定(bind)到列表框的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24079168/