Load or Save the Content of a RichTextBox


   
  
<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPF" Height="300" Width="300">
    <DockPanel>
        <StackPanel DockPanel.Dock="Top" Orientation="Horizontal">
            <Button Content="_New" Name="btnNew" Click="btnNew_Click" />
            <Button Content="_Open" Name="btnOpen" Click="btnOpen_Click" />
            <Button Content="_Save" Name="btnSave" Click="btnSave_Click" />
        </StackPanel>
        <RichTextBox DockPanel.Dock="Bottom" Name="rtbTextBox1"
                     HorizontalScrollBarVisibility="Visible" 
                     VerticalScrollBarVisibility="Visible">
            <FlowDocument>
                <Paragraph>this is a test</Paragraph>
                <Paragraph>this is a test</Paragraph>
            </FlowDocument>
        </RichTextBox>
    </DockPanel>
</Window>

//File:Window.xaml.cs
using Microsoft.Win32;
using System;
using System.IO;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Markup;    

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        private String currentFileName = String.Empty;

        public Window1()
        {
            InitializeComponent();
        }

        private void btnOpen_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.FileName = currentFileName;
            dialog.Filter = "XAML Files (*.xaml)|*.xaml";

            if (dialog.ShowDialog() == true)
            {
                currentFileName = dialog.FileName;
                {
                    using (FileStream stream = File.Open(currentFileName, FileMode.Open))
                    {
                        FlowDocument doc = XamlReader.Load(stream) as FlowDocument;
                        if (doc == null)
                        {
                            MessageBox.Show("Could not load document.", Title);
                        }
                        else
                        {
                            rtbTextBox1.Document = doc;
                        }
                    }
                }
            }
        }
        private void btnNew_Click(object sender, RoutedEventArgs e)
        {
            rtbTextBox1.Document = new FlowDocument();
            currentFileName = String.Empty;
        }
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.FileName = currentFileName;
            dialog.Filter = "XAML Files (*.xaml)|*.xaml";
            if (dialog.ShowDialog() == true)
            {
                currentFileName = dialog.FileName;
                using (FileStream stream = File.Open(currentFileName, FileMode.Create))
                {
                    XamlWriter.Save(rtbTextBox1.Document, stream);
                }
            }
        }
    }
}

   
    
     


Select all text from RichTextBox and cut


   
  
<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPF" Height="350" Width="500">
    <DockPanel>
        <StackPanel DockPanel.Dock="Top" Orientation="Horizontal">
            <StackPanel.Resources>
                <Style TargetType="{x:Type Button}">
                    <Setter Property="CommandTarget" Value="{Binding ElementName=rtbTextBox1}" />
                </Style>
            </StackPanel.Resources>
            <Button Content="Clear" Name="btnClear" Click="btnClear_Click" />
            <Separator Margin="5"/>
            <Button Content="Cu_t" Command="ApplicationCommands.Cut" />
            <Button Content="_Copy" Command="ApplicationCommands.Copy" />
            <Button Content="_Paste" Command="ApplicationCommands.Paste" />
            <Separator Margin="5"/>
            <Button Content="_Undo" Command="ApplicationCommands.Undo" />
            <Button Content="_Redo" Command="ApplicationCommands.Redo" />
            <Separator Margin="5"/>
            <Button Content="_Bold" Command="EditingCommands.ToggleBold" />
            <Button Content="_Italic" Command="EditingCommands.ToggleItalic" />
            <Button Content="Underline" Command="EditingCommands.ToggleUnderline" />
            <Separator Margin="5"/>
            <Button Content="_Right" Command="EditingCommands.AlignRight" />
            <Button Content="C_enter" Command="EditingCommands.AlignCenter" />
            <Button Content="_Left" Command="EditingCommands.AlignLeft" />
        </StackPanel>
        <RichTextBox DockPanel.Dock="Bottom" Name="rtbTextBox1"
                     HorizontalScrollBarVisibility="Visible" 
                     VerticalScrollBarVisibility="Visible">
            <FlowDocument>
                <Paragraph FontSize="12">
                    paragraph
                </Paragraph>
                <Paragraph FontSize="15">
                    paragraph
                </Paragraph>
                <Paragraph FontSize="18">A List</Paragraph>
                <List>
                    <ListItem>
                        <Paragraph>
                            <Bold>Bold List Item</Bold>
                        </Paragraph>
                    </ListItem>
                    <ListItem>
                        <Paragraph>
                            <Italic>Italic List Item</Italic>
                        </Paragraph>
                    </ListItem>
                    <ListItem>
                        <Paragraph>
                            <Underline>Underlined List Item</Underline>
                        </Paragraph>
                    </ListItem>
                </List>
            </FlowDocument>
        </RichTextBox>
    </DockPanel>
</Window>
//File:Window.xaml.cs
using System.Windows;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            rtbTextBox1.SelectAll();
            rtbTextBox1.Cut();
        }
    }
}

   
    
     


Add / Remove TextChanged event for RichTextBox


   
  

<Window x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Window1" Height="600" Width="800">
  <Grid>
    <RichTextBox x:Name="rtbTextContent" TextChanged="RichTextBox_TextChanged" />
  </Grid>
</Window>
//File:Window.xaml.cs
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace WpfApplication1
{

    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
        
        private void RichTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {

            TextRange textRange = new TextRange(rtbTextContent.Document.ContentStart, rtbTextContent.Document.ContentEnd);
            rtbTextContent.TextChanged -= RichTextBox_TextChanged;
            textRange.ClearAllProperties();
            ApplyFormatting();
            rtbTextContent.TextChanged += RichTextBox_TextChanged;
        }

        private void ApplyFormatting()
        {
            TextPointer tp = rtbTextContent.Document.ContentStart;
            tp = FindNextString(tp);

            TextPointer textRangeEnd = tp.GetPositionAtOffset(1, LogicalDirection.Forward);

            TextRange tokenTextRange = new TextRange(tp, tp.GetPositionAtOffset(1, LogicalDirection.Forward));

            tokenTextRange.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
        }

        private TextPointer FindNextString(TextPointer tp)
        {
            char[] buffer = new char[1];
            tp.GetTextInRun(LogicalDirection.Forward, buffer, 0, 1);
            return tp;
        }
    }
}

   
    
     


Get Caret Position in a RichTextBox by using RichTextBox.CaretPosition.GetPositionAtOffset


   
  



<Window 
  x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Window1" Height="600" Width="800">
  <DockPanel>
    <StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal">
      <TextBox x:Name="tbxInsertionText" Width="200" Margin="5,0" />
      <Button DockPanel.Dock="Bottom" Content="Insert" Click="btnInsert_Click"/>
    </StackPanel>
    <RichTextBox x:Name="rtbTextContent" />
  </DockPanel>
</Window>
//File:Window.xaml.cs
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void btnInsert_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(tbxInsertionText.Text))
            {
                return;
            }
            rtbTextContent.BeginChange();
            if (rtbTextContent.Selection.Text != string.Empty)
            {
                rtbTextContent.Selection.Text = string.Empty;
            }
            TextPointer tp = rtbTextContent.CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);
            rtbTextContent.CaretPosition.InsertTextInRun(tbxInsertionText.Text);
            rtbTextContent.CaretPosition = tp;
            rtbTextContent.EndChange();
            Keyboard.Focus(rtbTextContent);
        }
    }
}

   
    
     


Get selected text from RichTextBox by using RichTextBox.Selection.Text


   
  


<Window 
  x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Window1" Height="600" Width="800">
  <DockPanel>
    <StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal">
      <TextBox x:Name="tbxInsertionText" Width="200" Margin="5,0" />
      <Button DockPanel.Dock="Bottom" Content="Insert" Click="btnInsert_Click"/>
    </StackPanel>
    <RichTextBox x:Name="rtbTextContent" />
  </DockPanel>
</Window>
//File:Window.xaml.cs
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void btnInsert_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(tbxInsertionText.Text))
            {
                return;
            }
            rtbTextContent.BeginChange();
            if (rtbTextContent.Selection.Text != string.Empty)
            {
                rtbTextContent.Selection.Text = string.Empty;
            }
            TextPointer tp = rtbTextContent.CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);
            rtbTextContent.CaretPosition.InsertTextInRun(tbxInsertionText.Text);
            rtbTextContent.CaretPosition = tp;
            rtbTextContent.EndChange();
            Keyboard.Focus(rtbTextContent);
        }
    }
}

   
    
     


Programmatically Insert Text into a RichTextBox


   
  


<Window 
  x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Window1" Height="600" Width="800">
  <DockPanel>
    <StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal">
      <TextBox x:Name="tbxInsertionText" Width="200" Margin="5,0" />
      <Button DockPanel.Dock="Bottom" Content="Insert" Click="btnInsert_Click"/>
    </StackPanel>
    <RichTextBox x:Name="rtbTextContent" />
  </DockPanel>
</Window>
//File:Window.xaml.cs
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void btnInsert_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(tbxInsertionText.Text))
            {
                return;
            }
            rtbTextContent.BeginChange();
            if (rtbTextContent.Selection.Text != string.Empty)
            {
                rtbTextContent.Selection.Text = string.Empty;
            }
            TextPointer tp = rtbTextContent.CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);
            rtbTextContent.CaretPosition.InsertTextInRun(tbxInsertionText.Text);
            rtbTextContent.CaretPosition = tp;
            rtbTextContent.EndChange();
            Keyboard.Focus(rtbTextContent);
        }
    }
}

   
    
     


Event Setter from Resources


   
  
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Class="WpfApplication1.EventSetterDemo"
        Title="EventSetter Demo">
    <Window.Resources>
        <Style TargetType="{x:Type Button}">
            <EventSetter Event="Click" Handler="ButtonOnClick" />
        </Style>
    </Window.Resources>

    <StackPanel>
        <Button>Button 1</Button>
        <Button>Button 2</Button>
        <Button>Button 3</Button>
    </StackPanel>
</Window>
//File:Window.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace WpfApplication1
{
    public partial class EventSetterDemo : Window
    {

        public EventSetterDemo()
        {
            InitializeComponent();
        }
        void ButtonOnClick(object sender, RoutedEventArgs args)
        {
            Button btn = args.Source as Button;
            Console.WriteLine(btn.Content);
        }
    }
}