CR0N0S.LXIII
CR0N0S.LXIII

Reputation: 359

RichTextBox.Selection property not detected by Visual Studio. Missing using reference?

I want to use the selection property from my RichTextBox. I added a reference to PresentationFramework.dll on my project and a using reference to namespace System.Windows.Controls on my code. According to Microsoft documentation, that should work (RichTextBox.Selection Property)

However, Visual Studio fails to find myRichTextBox.Selection and gives me an error. Am I missing some reference or something?

The code throwing the error is this: it's a function that receives a RTF text and loads it into RichTextBox with rich format

 private void LoadRTF(string RTFtext)
 {
     MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(RTFtext));
     myRichTextBox.Selection.Load(stream, DataFormats.Rtf);
 } //LoadRTF

But the thing here is that Visual Studio doesn't recognize Selection property. Even a simple line like

 TextSelection ts = myRichTextBox.Selection; 

throws the same error

Upvotes: 0

Views: 479

Answers (1)

Timo Salomäki
Timo Salomäki

Reputation: 7189

Since you're using the Windows Forms RichTextBox control, Selection property is not available. You can use either the SelectedText or the SelectedRtf property to get the current selection content.

As for the part where you want to load content from a MemoryStream to the control, you can use the LoadFile(Stream, RichTextBoxStreamType) overload of the LoadFile method, like this:

private void LoadRTF(string RTFtext)
{
    MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(RTFtext));
    myRichTextBox.LoadFile(stream, RichTextBoxStreamType.RichText);
}

Lastly, if you really want to use the WPF RichTextBox control in a Winforms application, you can do it by using the ElementHost control, as described here.

Upvotes: 3

Related Questions