WPF TreeView 修改颜色

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}}"

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值