改变字符串颜色

好的,所以这是我上一期的问题,但我有代码:

private void btnTrans_Click(object sender, EventArgs e) { var abrvStr = inputBx.Text; foreach (var kvp in d) { abrvStr = abrvStr.Replace(kvp.Key, kvp.Value); } outputBx.Text = abrvStr; } 

基本上它是字典程序的一部分,因此当您在文本框1中输入一行文本时,它会出现在文本框2中,并且单词替换为文本框中的文本框1。 所以,如果黑色,白色在字典中,我进入墙壁是黑色的。 墙是白色的将出现在文本框2中。所以一切都很好。

现在是棘手的部分,我将如何改变它以允许我在文本框2中将更改的单词更改为红色。 所以在上面的例子中,墙是白色的 。 白色在文本的输出行中是红色的。

注意,我使用的是RichTextBoxes

C#语言!

以Oliver Jacot-Descombes为基础回答 :

 private void btnTrans_Click(object sender, EventArgs e) { var abrvStr = inputBx.Text; foreach (var kvp in d) { abrvStr = abrvStr.Replace(kvp.Key, kvp.Value); int start = abrvStr.IndexOf(kvp.Value); if(start >= 0) { richTextBox1.Text = abrvStr; richTextBox1.Select(start, kvp.Value.Length); richTextBox1.SelectionColor = Color.Red; } } } 

您可以对字典的值使用switch语句来获取要更改选择的颜色。 您需要修改它以适合字典中的值以及您想要的颜色。

您可以使用RichTextBoxSelectionColor属性。 首先选择要格式化的单词

 string word = "white"; int start = richTextBox1.Find(word); if (start >= 0) { richTextBox1.Select(start, word.Length); richTextBox1.SelectionColor = Color.Red; } 

在字典中将对KVP的引用添加到Textbox的Tag属性中。 当用户更改颜色时,从Tag属性获取KVP并更改KVP中的值。 我在我的博客C #Winforms和隐藏的关联标签上提供了对Tag属性的深入了解。 WPF / Silverlight也在控件上使用Tag属性。

—根据用户要求编辑—

我不确定为什么你需要枚举字典。 字典的重点是快速获得密钥。 我的示例使用它并且不执行for循环。

…初始化位置….

 var myDictionary = new Dictionary>() { { "Black", new Tuple("White", Color.Green) }, { "White", new Tuple("Black", Color.Red) } }; 

……(稍后在代码中)……

private void btnTrans_Click(object sender,EventArgs e)
{

 var key = inputBx.Text; // Let us say "White" if (myDictionary.ContainsKey(key)) { var targetColor = myDictionary[key]; // Just get the value outputBx.Select(0, targetColor.Item1.Length); outputBx.SelectionColor = targetColor.Item2; outputBx.Text = targetColor.Item1; } else { outputBx.Text = "Unknown"; } 

}

查看我关于词典的博客文章了解更多信息C#Dictionary Tricks