這似乎幾乎是不可能實現的,因爲沒有「RemovePropertyValue」的方法。我也嘗試了span,並得到了與你一樣的異常,所以我做了一個方法,收集TextRange中的所有段落,併爲每個分隔符創建一個跨度。我知道不太理想..無論如何,它適用於小例如,但可能很難與更復雜的東西一起工作。
private List<Span> m_spanList = new List<Span>();
private void c_setForegroundButton_Click(object sender, RoutedEventArgs e)
{
TextPointer textPointerStart = c_richTextBox1.Selection.Start;
TextPointer textPointerEnd = c_richTextBox1.Selection.End;
TextRange textRange = new TextRange(textPointerStart, textPointerEnd);
SetForeground(textRange);
}
private void c_clearForegroundButton_Click(object sender, RoutedEventArgs e)
{
foreach (Span span in m_spanList)
{
span.ClearValue(Span.ForegroundProperty);
}
}
public void SetForeground(TextRange textRange)
{
List<Paragraph> spannedParagraphs = new List<Paragraph>();
if (textRange.Start.Paragraph != null)
{
TextRange curRange = null;
Block cur = textRange.Start.Paragraph;
do
{
spannedParagraphs.Add(cur as Paragraph);
// Get next range
curRange = new TextRange(cur.ContentStart, cur.ContentEnd);
} while ((textRange.End.Paragraph == null || !curRange.Contains(textRange.End.Paragraph.ContentEnd)) && (cur = cur.NextBlock) != null);
}
if (spannedParagraphs.Count == 1)
{
Span span = new Span(c_richTextBox1.Selection.Start, c_richTextBox1.Selection.End);
span.Foreground = Brushes.Red;
m_spanList.Add(span);
}
else
{
for (int i = 0; i < spannedParagraphs.Count; i++)
{
if (i == spannedParagraphs.Count - 1)
{
Paragraph paragraph = spannedParagraphs[i];
// For some reason I get an exception here when I try this..
//m_span = new Span(paragraph.ElementStart, c_richTextBox1.Selection.End);
c_richTextBox1.Selection.Select(paragraph.ElementStart, c_richTextBox1.Selection.End);
Span span = new Span(c_richTextBox1.Selection.Start, c_richTextBox1.Selection.End);
span.Foreground = Brushes.Red;
m_spanList.Add(span);
}
else if (i == 0)
{
Paragraph paragraph = spannedParagraphs[i];
Span span = new Span(c_richTextBox1.Selection.Start, paragraph.ElementEnd);
span.Foreground = Brushes.Red;
m_spanList.Add(span);
}
else
{
Paragraph paragraph = spannedParagraphs[i];
Span span = new Span(paragraph.ElementStart, paragraph.ElementEnd);
span.Foreground = Brushes.Red;
m_spanList.Add(span);
}
}
}
}
感謝您的回覆,您的代碼的結果正是我所需要的,但那不是我正在尋找的。在我的情況下,用戶創建文本(在richTextbox上),因此他可以選擇不僅僅是一個特定的段落(或者只是其中的一部分)。我已經嘗試從所選文本範圍和「ClearValue(ForegroundProperty)」中創建跨度的所有內聯,但如果用戶選擇多個段落,則會出現錯誤:「'start'和'end'TextPointers不在同一段落「。 :( – Leo 2010-10-18 01:34:57
Meleak,謝謝...你的代碼做了詭計,我會看看最複雜的文檔,但現在我認爲它會正常工作。 – Leo 2010-10-19 14:47:44
我知道這是一個老問題,但我認爲答案是你真正在尋找的是@ jmlumpkin下面的答案。 – 2015-03-05 00:11:16