Click here to Skip to main content
15,880,543 members
Articles / Desktop Programming / WPF

WPF RichTextEditor with Toolbar

Rate me:
Please Sign up or sign in to vote.
4.86/5 (23 votes)
5 Jan 2010CPOL2 min read 128.1K   13.6K   64   22
WPF RichTextBox with standard Text-formatting possiblities
Window.jpg

Introduction

While playing around with WPF, I got stuck with the RichTextBox and their possibilities in comparison to the RichTextBox in WinFoms.
So I tried to develop a UserControl with the basic text-formatting functions in WPF.
This article is it.

I want to point out that I did use the Color Picker from Sacha Barber's article:

The Icons are from:

Using the Code

So, how does it all work. It is rather simple, my RTF-Editor is a WPF UserControl-Project.
It can easily be used like I demonstrated it in my TestApplication whose XAML looks like this:

XML
<Window x:Class="TestApp.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:rtf="clr-namespace:RTFEditor;assembly=RTFEditor"
    Title="Window1" Height="300" Width="300">
    <DockPanel>
        <rtf:RTFBox></rtf:RTFBox>
    </DockPanel>   
</Window>     

The RTFBox class is my RTF-Editor.
The UserInterface consists of a RichTextBox, a StatusBar and two ToolBars which hold all the buttons for text-formatting.

The first toolbars XAML looks like this:

XML
  <ToolBar x:Name="ToolBarOben" DockPanel.Dock="Top">
    <Button x:Name="ToolStripButtonOpen" 
                        Click="ToolStripButtonOpen_Click">
    <Image Source="Images\Open.png" Stretch="None"/>
</Button>
<Button x:Name="ToolStripButtonPrint" 
                        Click="ToolStripButtonPrint_Click">
    <Image Source="Images\Print.png" Stretch="None"/>    
</Button>
<Separator/>
<Button x:Name="ToolStripButtonCut" 
                        Command="ApplicationCommands.Cut" ToolTip="Cut">
    <Image Source="Images\Cut.png" Stretch="None"/>
</Button>
<Button x:Name="ToolStripButtonCopy" 
                        Command="ApplicationCommands.Copy" ToolTip="Copy">
    <Image Source="Images\Copy.png" Stretch="None"/>    
</Button>
<Button x:Name="ToolStripButtonPaste" 
                        Command="ApplicationCommands.Paste" ToolTip="Paste">
    <Image Source="Images\Paste.png" Stretch="None"/>    
</Button>
<Button x:Name="ToolStripButtonUndo" 
                        Command="ApplicationCommands.Undo" ToolTip="Undo">
    <Image Source="Images\Undo.png" Stretch="None"/>    
</Button>
<Button x:Name="ToolStripButtonRedo" 
                        Command="ApplicationCommands.Redo" ToolTip="Redo">
    <Image Source="Images\Redo.png" Stretch="None"/>    
</Button>
<Separator/>
<ComboBox x:Name="Fonttype" ItemsSource="{Binding Mode=OneWay, 
                                             Source={StaticResource FontListKlasse}}" 
                          DropDownClosed="Fonttype_DropDownClosed" />
        <ComboBox x:Name="Fontheight" ItemsSource="{Binding Mode=OneWay, 
                                             Source={StaticResource FontHeightKlasse}}"  
                          DropDownClosed="Fontheight_DropDownClosed" />
</ToolBar> 

As you can see, it is really straightforward. I used the ApplicationCommands for Cut, Copy, Paste, Undo, Redo and defined the necessary Handler for Open, Print.
A bit more complex are the ComboBoxes for FontType and FontHeight. I used a OneWay Binding to static resources that I defined in my XAML like this:

XML
<UserControl.Resources>
        <ObjectDataProvider x:Key="FontListKlasse" d:IsDataSource="True" 
                            ObjectType="{x:Type RTFEditor:FontList}"/>
        <ObjectDataProvider x:Key="FontHeightKlasse" d:IsDataSource="True" 
                            ObjectType="{x:Type RTFEditor:FontHeight}"/>
    </UserControl.Resources>   

Here are the two classes FontHeight and FontList that hold the information.

C#
class FontList : ObservableCollection<string> 
    { 
        public FontList() 
        {
            foreach (FontFamily f in Fonts.SystemFontFamilies)
            {                
                this.Add(f.ToString());                
            }  
        }   
    }
class FontHeight : ObservableCollection<string>
    { 
        public FontHeight()
        {
            this.Add("8");
            this.Add("9");
            this.Add("10");
            this.Add("11");
            this.Add("12");
            this.Add("14");
            this.Add("16");
            this.Add("18");   
            this.Add("20");
            this.Add("22");
            this.Add("24");
            this.Add("26");
            this.Add("28");
            this.Add("36");
            this.Add("48");
            this.Add("72");
        }        
    }  

The second ToolBar is similar so without pasting the full XAML code:
I used ToggleButtons for the textstyle (bold, italic, ...) and textalignment(right, left, ...).
If possible, I used EditingCommands like this:

XML
<ToggleButton x:Name="ToolStripButtonBold" 
              Command="EditingCommands.ToggleBold" 
              ToolTip="Bold">
              <Image Source="Images\Bold.png" Stretch="None"/>                
</ToggleButton>

There is no EditingCommand for strikethrough formatting, so I did this via TextDecorations:

C#
private void ToolStripButtonStrikeout_Click(object sender, 
                                            System.Windows.RoutedEventArgs e)
        {            
            TextRange range = new TextRange(RichTextControl.Selection.Start, 
                                            RichTextControl.Selection.End);

            TextDecorationCollection tdc = 
                (TextDecorationCollection)RichTextControl.
                     Selection.GetPropertyValue(Inline.TextDecorationsProperty);
            if (tdc == null || !tdc.Equals(TextDecorations.Strikethrough))
            {
                tdc = TextDecorations.Strikethrough;
            }
            else
            {
                tdc = new TextDecorationCollection();
            }
            range.ApplyPropertyValue(Inline.TextDecorationsProperty, tdc);
        } 

As there is no ColorDialog in WPF like the one in WinForms, I used one from Sacha Barber for Textforecolor and Textbackgroundcolor.

C#
private void ToolStripButtonTextcolor_Click
			(object sender, RoutedEventArgs e)
        {
            ColorDialog colorDialog = new ColorDialog();
            //colorDialog.Owner = this;
            if ((bool)colorDialog.ShowDialog())
            {
                TextRange range = new TextRange(RichTextControl.Selection.Start, 
                    RichTextControl.Selection.End);

                range.ApplyPropertyValue(FlowDocument.ForegroundProperty, 
                    new SolidColorBrush(colorDialog.SelectedColor));      
            }
        }

For superscript and subscript exist EditingCommands but they do only work for OpenType Fonts. So instead of using them, I changed BaselineAlignments to display sub/superscript for all fonts like this:

C#
private void ToolStripButtonSubscript_Click(object sender, RoutedEventArgs e)
        {
            var currentAlignment = 
              RichTextControl.Selection.GetPropertyValue
			(Inline.BaselineAlignmentProperty);

            BaselineAlignment newAlignment = 
              ((BaselineAlignment)currentAlignment == 
				BaselineAlignment.Subscript) ? 
                                 BaselineAlignment.Baseline : 
				BaselineAlignment.Subscript;
            RichTextControl.Selection.ApplyPropertyValue
				(Inline.BaselineAlignmentProperty, 
                                         newAlignment);
        } 

I added a Statusbar for displaying the line and columnnumber and a zoom function. The XAML is straightforward.

To get the line number, I had to start from the beginning and count all lines to the current cursor position like this:

C#
private int LineNumber()
        {
            TextPointer caretLineStart = 
                           RichTextControl.CaretPosition.GetLineStartPosition(0);
            TextPointer p = RichTextControl.Document.ContentStart.GetLineStartPosition(0);
            int currentLineNumber = 1;
            
            while (true)
            {
                if (caretLineStart.CompareTo(p) < 0)
                {
                    break;
                }
                int result;
                p = p.GetLineStartPosition(1, out result);
                if (result == 0)
                {
                    break;
                }
                currentLineNumber++;
            }
            return currentLineNumber;
        }

To get the column number, I could use the GetOffsetToPosition function like this:

C#
private int ColumnNumber()
        {
            TextPointer caretPos = RichTextControl.CaretPosition;
            TextPointer p = RichTextControl.CaretPosition.GetLineStartPosition(0);
            int currentColumnNumber = Math.Max(p.GetOffsetToPosition(caretPos) - 1, 0);

            return currentColumnNumber;
        } 

At this point I realized that the WinForms RichTextBox offers a zoom function, the WPF RichTextBox doesn't. I did not find a way to implement one. (Any help in this regard will be appreciated.)

After I finished with the mentioned basic Texteditor functions, I wanted a possibility to get the RTF-content out of the RichTextControl, means the text with the rich text formatting. The WPF RichTextBox holds no straightforward way to get this so I did this:

C#
public string GetRTF()
        {
            TextRange range = new TextRange(RichTextControl.Document.ContentStart, 
                RichTextControl.Document.ContentEnd);

            // Exception abfangen für StreamReader und MemoryStream
            try
            {
                using (MemoryStream rtfMemoryStream = new MemoryStream())
                {
                    using (StreamWriter rtfStreamWriter = 
                                             new StreamWriter(rtfMemoryStream))
                    {
                        range.Save(rtfMemoryStream, DataFormats.Rtf);

                        rtfMemoryStream.Flush();
                        rtfMemoryStream.Position = 0;
                        StreamReader sr = new StreamReader(rtfMemoryStream);
                        return sr.ReadToEnd();
                    }
                }
            }
            catch (Exception)
            {
                throw;                
            }
        }  

And the other direction looks like this:

C#
public void SetRTF(string rtf)
        {
            TextRange range = new TextRange(RichTextControl.Document.ContentStart, 
                RichTextControl.Document.ContentEnd);
         
            try
            {
                using (MemoryStream rtfMemoryStream = new MemoryStream())
                {
                    using (StreamWriter rtfStreamWriter = 
                                                   new StreamWriter(rtfMemoryStream))
                    {
                        rtfStreamWriter.Write(rtf);
                        rtfStreamWriter.Flush();
                        rtfMemoryStream.Seek(0, SeekOrigin.Begin);

                        range.Load(rtfMemoryStream, DataFormats.Rtf);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        } 

Your Opinion

I'm very interested in your opinion about the article and the code. Please leave some comments and let me know if the article could help you in any way.

History

  • 5th January, 2010: Initial post 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionThanks Pin
Member 1046438412-Jul-22 4:25
Member 1046438412-Jul-22 4:25 
QuestionWould you like an About Box credit? Pin
Member 1032625625-Sep-17 1:37
Member 1032625625-Sep-17 1:37 
GeneralMy vote of 3 Pin
raiserle17-Jul-17 4:31
raiserle17-Jul-17 4:31 
QuestionUse DLL in vb .NET Project Pin
trC_9-Jun-17 13:32
trC_9-Jun-17 13:32 
QuestionSet RTF content through MemoryStream Pin
00zhang18-Apr-16 13:49
00zhang18-Apr-16 13:49 
QuestionThanks You, Great Job Pin
Henka.Programmer7-Mar-16 0:40
Henka.Programmer7-Mar-16 0:40 
QuestionFormating disappears in the beginning Pin
Jesper Gissel5-Aug-14 2:42
Jesper Gissel5-Aug-14 2:42 
QuestionI have great difficulty to activate GregorPross' otherwise praised "WPF RichTextEditor with Toolbar" software Pin
Member 995312118-Jun-13 16:45
Member 995312118-Jun-13 16:45 
AnswerRe: I have great difficulty to activate GregorPross' otherwise praised "WPF RichTextEditor with Toolbar" software Pin
Member 995312121-Jun-13 3:36
Member 995312121-Jun-13 3:36 
AnswerRe: I have great difficulty to activate GregorPross' otherwise praised "WPF RichTextEditor with Toolbar" software Pin
Member 995312121-Jun-13 16:28
Member 995312121-Jun-13 16:28 
SuggestionGreat, I'm using it Pin
Jetteroh13-Jun-12 3:11
Jetteroh13-Jun-12 3:11 
GeneralZoom functionality Pin
Le Duc Anh13-Feb-11 20:21
professionalLe Duc Anh13-Feb-11 20:21 
GeneralMy vote of 5 Pin
TweakBird22-Jan-11 2:18
TweakBird22-Jan-11 2:18 
QuestionFind / Replace Functionality(text with sub or super script also) Pin
TweakBird22-Jan-11 2:17
TweakBird22-Jan-11 2:17 
GeneralMy vote of 5 Pin
Member 287883929-Sep-10 5:46
Member 287883929-Sep-10 5:46 
GeneralBold / Italics toolbar buttons Pin
Wjousts26-Jul-10 10:07
Wjousts26-Jul-10 10:07 
QuestionSubscripted/superscripted characters lost from a saved rtf. Pin
VishalvPatil27-Jun-10 22:57
VishalvPatil27-Jun-10 22:57 
AnswerRe: Subscripted/superscripted characters lost from a saved rtf. Pin
ketansnadar30-Aug-12 2:12
ketansnadar30-Aug-12 2:12 
GeneralThanks Pin
mpggkobol4-Jun-10 21:47
mpggkobol4-Jun-10 21:47 
GeneralBinding Pin
Wizard_Memfis3-Jun-10 9:22
Wizard_Memfis3-Jun-10 9:22 
GeneralNifty... Pin
ProtoBytes5-Jan-10 3:23
ProtoBytes5-Jan-10 3:23 
GeneralRe: Nifty... Pin
GregorPross6-Jan-10 1:52
GregorPross6-Jan-10 1:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.