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.vb
Imports Microsoft.Win32
Imports System
Imports System.IO
Imports System.Windows
Imports System.Windows.Documents
Imports System.Windows.Markup
Namespace WpfApplication1
Public Partial Class Window1
Inherits Window
Private currentFileName As [String] = [String].Empty
Public Sub New()
InitializeComponent()
End Sub
Private Sub btnOpen_Click(sender As Object, e As RoutedEventArgs)
Dim dialog As New OpenFileDialog()
dialog.FileName = currentFileName
dialog.Filter = "XAML Files (*.xaml)|*.xaml"
If dialog.ShowDialog() = True Then
currentFileName = dialog.FileName
If True Then
Using stream As FileStream = File.Open(currentFileName, FileMode.Open)
Dim doc As FlowDocument = TryCast(XamlReader.Load(stream), FlowDocument)
If doc Is Nothing Then
MessageBox.Show("Could not load document.", Title)
Else
rtbTextBox1.Document = doc
End If
End Using
End If
End If
End Sub
Private Sub btnNew_Click(sender As Object, e As RoutedEventArgs)
rtbTextBox1.Document = New FlowDocument()
currentFileName = [String].Empty
End Sub
Private Sub btnSave_Click(sender As Object, e As RoutedEventArgs)
Dim dialog As New SaveFileDialog()
dialog.FileName = currentFileName
dialog.Filter = "XAML Files (*.xaml)|*.xaml"
If dialog.ShowDialog() = True Then
currentFileName = dialog.FileName
Using stream As FileStream = File.Open(currentFileName, FileMode.Create)
XamlWriter.Save(rtbTextBox1.Document, stream)
End Using
End If
End Sub
End Class
End Namespace
Related examples in the same category