爲什麼不使用RichEditBox?這裏的東西我很快就颳起了:
<RichEditBox x:Name="tb" TextChanged="tb_TextChanged" />
private void tb_TextChanged(object sender, RoutedEventArgs e)
{
// we don't want this handler being called as a result of
// formatting changes being made here
tb.TextChanged -= tb_TextChanged;
var doc = tb.Document;
doc.BatchDisplayUpdates();
try
{
string text;
doc.GetText(TextGetOptions.None, out text);
if (text.Length == 0)
return;
// check if this word starts with a hash
var start = doc.Selection.StartPosition - 1;
while (true)
{
if (start < 0 || char.IsWhiteSpace(text[start]))
return;
if (text[start] == '#')
break;
start--;
}
// find the end of the word
var end = doc.Selection.StartPosition;
while (start < text.Length && !char.IsWhiteSpace(text[end]))
end++;
// set color
doc.GetRange(start, end).CharacterFormat.ForegroundColor = Colors.RoyalBlue;
}
finally
{
doc.ApplyDisplayUpdates();
tb.TextChanged += tb_TextChanged;
}
}
可以很明顯的優化更多。它不支持格式化粘貼文本,這是一個練習:)
因爲它不是一個贏得電話答案我不會將它標記爲重複,但[this](http://stackoverflow.com/questions/3707120/how-to-the-rich-text-from-the-rich-text-it)看起來像一條不錯的路線。 – 2014-12-02 15:20:23