2012-10-08 35 views
4

您好,我已經在顯示或在我的RichTextBox到其他RichTextBox的轉化中的數據有問題......如何將數據從RichTextBox的傳送到另一RichTextBox的WPF C#

richtextbox1.Document = richtextbox2.Document; //This will be the idea.. 

實際上正是我打算做的是,我想從我的數據庫轉移我的數據我的列表視圖將顯示爲它是什麼

SQLDataEHRemarks = myData["remarks"].ToString();// Here is my field from my database which is set as Memo 
RichTextBox NewRichtextBox = new RichTextBox();// Now i created a new Richtextbox for me to take the data from SQLDataEHRemarks... 
NewRichtextBox.Document.Blocks.Clear();// Clearing 
TextRange tr2 = new TextRange(NewRichtextBox.Document.ContentStart, NewRichtextBox.Document.ContentEnd);// I found this code from other forum and helps me a lot by loading data from the database.... 
MemoryStream ms2 = GetMemoryStreamFromString(SQLDataEHRemarks);//This will Convert to String 
tr2.Load(ms2, DataFormats.Rtf);//then Load the Data to my NewRichtextbox 

現在我想要做的是,我去這個數據加載到我的ListView ..或其他類似的控制textblock或textbox ...

_EmpHistoryDataCollection.Add(new EmployeeHistoryObject{ 
EHTrackNum = tr2.ToString() // The problem here is it will display only the first line of the paragraph.. not the whole paragraph 
}); 

回答

3

使用的TextRange代替.ToString()

方法的Text屬性來獲取RichTextBox的內容作爲字符串:

public static string GetStringFromRichTextBox(RichTextBox richTextBox) 
{ 
    TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); 
    return textRange.Text; 
} 

方法得到一個RichTextBox豐富文本的內容:

public static string GetRtfStringFromRichTextBox(RichTextBox richTextBox) 
{ 
    TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); 
    MemoryStream ms = new MemoryStream(); 
    textRange.Save(ms, DataFormats.Rtf); 

    return Encoding.Default.GetString(ms.ToArray()); 
} 

編輯:你可以把從GetRtfStringFromRichTextBox()在另一個RichText控制做的富文本返回以下:

FlowDocument fd = new FlowDocument(); 
MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(richTextString)); 
TextRange textRange = new TextRange(fd.ContentStart, fd.ContentEnd); 
textRange.Load(ms, DataFormats.Rtf); 
richTextBox.Document = fd; 
+0

感謝ü這麼多... :)順便說一下如何回合從列表視圖或文本框將數據發送到RichTextBox的?對於這個... ... –

+0

@KenshiHemura檢查我的答案的最後一點,設置RichTextBox的內容的一種方法。 – Eirik