請嘗試以下代碼:
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代碼。
通過
System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml(color);
richTextBox1.SelectionColor = col;
更換
richTextBox1.SelectionColor = Color.FromName(color);
和
color='#ffff80ff'
嘗試更換
使用一些所見即所得的編輯器。看到這個鏈接http://ckeditor.com/ – shajivk 2012-07-30 11:38:00