[英]How to get all text from RichTextBox in WPF
我需要從 WPF RichTextBox 中准確獲取所有文本。
每個人( 如何將 WPF 富文本框轉換為字符串, RichTextBox (WPF) 沒有字符串屬性“Text” ,http://msdn.microsoft.com/en-us/library/ms754041(v=vs.110) .aspx和更多)同意這樣的代碼:
public static string GetText(RichTextBox rtb)
{
TextRange textRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
string text = textRange.Text;
return text;
}
但它添加了一個尾隨的“\\r\\n”。 在一個非常簡單的情況下:
<RichTextBox x:Name="mRichTextBox">
<FlowDocument>
<Section>
<Paragraph>
<Run Text="The dog is brown. The cat is black."/>
</Paragraph>
</Section>
</FlowDocument>
</RichTextBox>
我得到:
“狗是棕色的。貓是黑色的。\\r\\n”
它可以被視為一個小問題,但我真的需要確切的文字。
謝謝。
如果您不需要多行,您可以禁用它,應該不會有這個問題。
你也可以像這樣刪除它們:
string text = textRange.Text.Replace(Environment.NewLine, "");
此外,如果您只想刪除最后一次出現,您可以使用這樣的函數:
public static string ReplaceLastOccurrence(string Source, string Find, string Replace)
{
int Place = Source.LastIndexOf(Find);
string result = Source.Remove(Place, Find.Length).Insert(Place, Replace);
return result;
}
並像這樣使用它。
string text = ReplaceLastOccurrence(textRange.Text,Environment.NewLine,"");
每次你有一個,你都會在最后得到一個新行,所以一定要妥善處理它。
但是你得到的是實際的文本。
你不認為一個段落應該以新行結尾嗎?
試試這個並將粘貼從屏幕復制到記事本
<RichTextBox x:Name="mRichTextBox">
<FlowDocument>
<Section>
<Paragraph/>
<Paragraph/>
<Paragraph>
<Run Text="The dog is brown. The cat is black."/>
</Paragraph>
</Section>
</FlowDocument>
</RichTextBox>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.