使用组合框来更改文本框的前景色

时间:2015-07-23 03:17:17

标签: c# winforms combobox

如何使用组合框项目更改多个文本框的前景?

我已将此方法中的所有可用颜色枚举到组合框中。

private void getFontColor()
{
    foreach (KnownColor color in Enum.GetValues(typeof(KnownColor)))
    {
        cmbColor.Items.Add(color);
    }
}

所以现在当用户选择组合框上的颜色时,我希望改变几个文本框的前景

private void cmbColor_SelectedIndexChanged(object sender, EventArgs e)
{
    //How do I use the selected item and assign it as forecolor
    //SelectedItem is an object

    //textBox1.ForeColor = ??

    //i tried this but doesnt work

    Color selectedColor = (Color)cmbColor.SelectedItem;
    textBox1.ForeColor = selectedColor;
}

2 个答案:

答案 0 :(得分:1)

您的SelectedItemKnownColor,而不是Color,因此您需要从Color创建KnownColor

Color selectedColor = Color.FromKnownColor(selectedKnownColor)

答案 1 :(得分:0)

Forecolor表示文本框文本的颜色,您提到的代码工作正常

我做了以下

private void Form1_Load(object sender, EventArgs e)
    {
        Dictionary<Color, string> ss = new Dictionary<Color, string>();
        comboBox1.Items.Add(Color.Red);
        comboBox1.Items.Add(Color.Green);
    }

和comboBox1_SelectedIndexChanged是

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Color selectedColor = (Color)comboBox1.SelectedItem;
        textBox1.ForeColor = selectedColor;
    }

它工作正常。