请尝试以下代码:
private void button1_Click(object sender, EventArgs e)
{
var textConfiguration = XDocument.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.xml"));
if (textConfiguration != null)
{
textConfiguration.Descendants("Configuration").Descendants("text").ToList().ForEach(text =>
{
font = text.Attribute("font").Value;
color = text.Attribute("color").Value;
fontsize = text.Attribute("font-size").Value;
textToAppend = text.Value;
});
}
richTextBox1.SelectionColor = Color.FromName(color);
richTextBox1.SelectionFont = new Font(font, int.Parse(fontsize), FontStyle.Regular);
richTextBox1.AppendText(textToAppend);
}
XML 文件是这样的:
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<text font='Verdana' color='Green' font-size='8'>The Formatted Text</text>
</Configuration>
我希望这会给你一个想法。
如果你有多个文本块,你可以修改代码如下:
private void button1_Click(object sender, EventArgs e)
{
var textConfiguration = XDocument.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.xml"));
if (textConfiguration != null)
{
textConfiguration.Descendants("Configuration").Descendants("text").ToList().ForEach(text =>
{
font = text.Attribute("font").Value;
color = text.Attribute("color").Value;
fontsize = text.Attribute("font-size").Value;
textToAppend = text.Value;
richTextBox1.SelectionColor = Color.FromName(color);
richTextBox1.SelectionFont = new Font(font, int.Parse(fontsize), FontStyle.Regular);
richTextBox1.AppendText(textToAppend);
});
}
}
XML将是这样的
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<text font='Verdana' color='Green' font-size='8'>The </text>
<text font='Verdana' color='Red' font-size='8'>Formatted </text>
<text font='Verdana' color='Blue' font-size='8'>Text</text>
</Configuration>
我再次修改了代码,现在您可以在 XML 文件中包含 Hex coloe 代码。
代替
richTextBox1.SelectionColor = Color.FromName(color);
经过
System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml(color);
richTextBox1.SelectionColor = col;
并更换
color='Green'
经过
color='#ffff80ff'