Search code examples
c#wpfxamlrichtextboxdocument

richtextbox to string


I have a richtextbox bound to a menu item to allow bold, italic and underline aswell as cut copy and paste. But how do you take the richtextbox content and turn it into a string from code behind which will carry the bold, italic etc?

        </DockPanel>
            <DockPanel Height="259" VerticalAlignment="Bottom">
            <Menu DockPanel.Dock="Top">
                <MenuItem Header="Edit">
                    <MenuItem Command="Cut" Header="_Cut" />
                    <MenuItem Command="Copy" Header="C_opy" />
                    <MenuItem Command="Paste" Header="_Paste" />
                </MenuItem>
            </Menu>
            <ToolBarTray DockPanel.Dock="Top">
                <ToolBar>
                    <Button Command="Cut" Content="Cut" />
                    <Button Command="Copy" Content="Copy" />
                    <Button Command="Paste" Content="Paste" />
                            <ToggleButton MinWidth="40"
                    Command="EditingCommands.ToggleBold"
                    CommandTarget="{Binding ElementName=XAMLRichBox}"
                    TextBlock.FontWeight="Bold">B</ToggleButton>
                            <ToggleButton MinWidth="40"
                    Command="EditingCommands.ToggleItalic"
                    CommandTarget="{Binding ElementName=XAMLRichBox}"
                    TextBlock.FontStyle="Italic">I</ToggleButton>
                            <ToggleButton MinWidth="40"
                    Command="EditingCommands.ToggleUnderline"
                    CommandTarget="{Binding ElementName=XAMLRichBox}">
                                <TextBlock TextDecorations="Underline">U</TextBlock>
                            </ToggleButton>
                        </ToolBar>
            </ToolBarTray>
                <RichTextBox HorizontalAlignment="Left" Margin="0,0,0,0" Name="richTextBox1"  Height="211" VerticalAlignment="Top" Width="398" />

In the code behind I was trying to do this (not sure on how to do it) but the textblock just comes out as normal text it doesnt contain the bold etc.

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        string myText = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text;
        textBlock1.Text = myText;

Solution

  • The simple answer to your question is: you can't. A string contains no formatting information. You'll need to store the RichTextBox's content in a format that supports text formatting, like RTF.