如何在WPF C#中将数据从一个RichTextBox传输到另一个RichTextBox

5

嗨,我有一个问题,就是无法在我的 RichTextBox 控件中正确显示或传输数据到其他 RichTextBox 控件中...

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
}); 
2个回答

4

使用TextRangeText属性代替.ToString()方法。

获取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;

非常感谢您... :) 顺便问一下,从listview或textbox发送的数据如何发送到richtextbox?对此很抱歉... - Kenshi Hemura
@KenshiHemura,请查看我的答案的最后一部分,了解设置RichTextBox内容的一种方法。 - Eirik
获取 RichTextBox 的内容作为字符串,只需要像这样做: (在 VB.Net 中) Dim strText as string = MyRTB.text - Chris Raisin
回复晚了,但更优化的方法是使用“StreamReader”从中获取字符串,这样可以避免创建整个数组,然后再创建一个新的字符串对象。 - ABPerson

0

获取 RichTextBox 的内容作为字符串,不是简单地像以下代码一样吗(在 VB.Net 中)

Dim strText as string = MyRTB.text

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接