c# - 将随机颜色绑定(bind)到列表框的项目

标签 c# xaml windows-phone-8 listbox

我想在列表框中生成不同颜色的项目。例如 - 每个项目都有不同颜色的矩形。我做不到。 到目前为止我已经创建了一个这样的类

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>

完成所有这些后,我得到这样的结果 -

SampleImage1

重新启动应用程序后,我得到了这个

SampleImage2

虽然每当我运行应用程序时我都会得到随机颜色。但一种颜色应用于所有矩形。

我不知道如何获得想要的结果。 我想要这样的东西 -

enter image description here

如有任何帮助,我们将不胜感激。

最佳答案

重点是,仅当您创建 RandomColorGenerator 类时才生成 RabdomBrush。

每次调用时都应该生成新的 RandomBrush。有点像这样:

public class RandomColorGenerator
{
  public Color randomBrush { 

    get {return generateRandomColor(); }

}
....

关于c# - 将随机颜色绑定(bind)到列表框的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24079168/

相关文章:

c# - TabControl 项目标题文本在旋转选项卡后显得模糊

xaml - 如何使用 MVVM 将 XAML 标签与 TapGestureRecognizer 绑定(bind)?

xaml - Silverlight Xaml 和资源中的 StringFormat

windows-phone-8 - 如何在 Windows Phone 8 中设置视频录制分辨率。

c# - 实体属性值 (EAV) 框架?

c# - PowerShell Get-ChildItem 在 C# 中调用

c# - 在 PropertyGrid 中使用自定义颜色选择器对话框

c# - 显示一个 Pivot 但在另一个 Pivot 中注册水龙头的 Pivot 控件

windows-phone-7 - Windows Phone 8 上的 Windows Phone 7 应用程序

c# - 即使MSDN另有建议,为什么Parallel.ForEach比AsParallel()。ForAll()快得多?