tamthoima Mr

tamthoima Mr

  • 2.1k
  • 1
  • 1.9k

Format Multi-Font in System.Windows.Forms.RichTextBox with FlowDocument

Nov 4 2012 9:34 PM

I want to use Richtextbox to store text with format in SQL database. I love the way System.Windows.Forms.RichTextBox handle binding RTF format but i hate the way it change multi-font format. So I use flowdocument to handle multi-font format. Below is my code

Imports System.Windows.Forms
Imports System.Windows.Documents
Imports System.IO
Imports System.Text
    Private Sub chkbBold_Click(sender As Object, e As EventArgs) Handles chkbBold.Click
                Dim SelStart As Integer = rtbOtherInfo.SelectionStart
                Dim SelLength As Integer = rtbOtherInfo.SelectionLength

                Dim fdTmp As FlowDocument = New FlowDocument()
                Dim inStream As MemoryStream = New MemoryStream(Encoding.ASCII.GetBytes(rtbOtherInfo.SelectedRtf))
                Dim outStream As New MemoryStream
                Dim textRangeTmp As TextRange = New TextRange(fdTmp.ContentStart, fdTmp.ContentEnd)

                textRangeTmp.Load(inStream, DataFormats.Rtf)

                'Toggle chkbBold state
                If chkbItalic.Checked = True Then
                    textRangeTmp.ApplyPropertyValue(TextElement.FontWeightProperty, Windows.FontWeights.Bold)
                    textRangeTmp.ApplyPropertyValue(TextElement.FontWeightProperty, Windows.FontWeights.Normal)
                End If
                textRangeTmp.Save(outStream, DataFormats.Rtf)

                rtbOtherInfo.SelectedRtf = System.Text.ASCIIEncoding.Default.GetString(outStream.ToArray())
                rtbOtherInfo.SelectionStart = SelStart
                rtbOtherInfo.SelectionLength = SelLength

            Catch ex As Exception
            End Try
    End Sub

But i see some schange behavior of richtextbox:
- in some selected text in richtextbox, this code work well, but in some case, there's nothing change in richtextbox after chkbBold_Click.
- some time I can set selected text to Bold but cannot set the selected text back to normal (with the same selected text)

Please kindly help to show me what im I wrong?
Please also kindly share you ideas.

Thank you all