C#WPF使用文本更改颜色 [英] C# WPF change colour with text

查看:102
本文介绍了C#WPF使用文本更改颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用文本coz更改某物的颜色我知道此代码

how do i change the colour of something using text coz i know this code

this.comboBox1.Background = new SolidColorBrush(Colors.DarkBlue);



我想做这个事

this.comboBox1.Background = new SolidColorBrush(comboBox1.selecteditem);



and i wanna do thing this this

this.comboBox1.Background = new SolidColorBrush(comboBox1.selecteditem);

推荐答案

尝试使用此功能

Try this function

public Color GetColorFromText(string colorString)
        {
            Type colorType = (typeof(System.Windows.Media.Colors));
            if (colorType.GetProperty(colorString) != null)
            {
                object colour = colorType.InvokeMember(colorString, BindingFlags.GetProperty, null, null, null);
                if (colour != null) ;
                {
                    return (Color)colour;
                }
            }
            return Color.FromRgb(255,255,255);
        }



那么你可以这样称呼



then you can call it like this

this.comboBox1.Background = new SolidColorBrush(GetColorFromText("Blue"));



希望这对您有帮助



Hope this helps


我宁愿以XAML方式执行此操作,而无需触及后面的代码.

I would prefer doing this in the XAML way without touching the code-behind.

<ComboBox Height="23"

          Name="comboBox1"

          Background="{Binding Path=SelectedItem, RelativeSource={RelativeSource Self}}"/>



使用SelectedItem 属性,并将RelativeSource设置为self(其组合框为"combobox1").如果您想从另一个组合框设置背景,只需执行以下绑定即可:{Binding Path=SelectedItem, ElementName=comboBox2}
是不是很简单!



Use the SelectedItem property with the RelativeSource set as self(its the same combobox "combobox1"). Had it been the case where you wanted to set the background from another combobox, just do this binding: {Binding Path=SelectedItem, ElementName=comboBox2}
Simple isn''t it!


这行不通.
您需要通过将所选项目值映射到相应的COlors 枚举值,将combobox1中的值转换为有效的颜色枚举.
This wont work.
You wilo need to convert the value inside combobox1 into a valid color enum by mapping the selected item value to the corresponding COlors enum value.


这篇关于C#WPF使用文本更改颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆