Text Editor

Text Editing is one of the most common tasks performed, and using Silverlight with Windows Phone 7 it is possible to create a basic Text Editor with Open and Save support for the device.

Printer Friendly Download Tutorial (786KB) Download Source Code (20KB)

Step 1

Start Microsoft Visual Studio 2010 Express for Windows Phone, then Select File then New Project... Select "Visual C#" then "Silverlight for Windows Phone" and then "Windows Phone Application" from Templates, select a Location if you wish, then enter a name for the Project and then click OK, see below:

New Project

Step 2

A Windows Phone application Page named MainPage.xaml should then appear, see below:

MainPage.xaml

Step 3

Right Click on the App.xaml Entry in the Solution Explorer for the Solution and choose "View Code" then in the Code View for App.xaml.css, above "public App()" type the following:

private string _filename = "";
private object _content = null;

public string Filename
{
  get { return _filename; }
  set { _filename = value; }
}

public object Content
{
  get { return _content; }
  set { _content = value; }
}

See below:

App Filename and Content

Step 4

Return to the MainPage Designer View by selecting the "MainPage.xaml" Tab. Then in the XAML Pane above the <Grid x:Name="LayoutRoot" Background="{StaticResource PhoneBackgroundBrush}"> line type the following XAML:

<phone:PhoneApplicationPage.ApplicationBar>
  <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
    <shell:ApplicationBar.MenuItems>
      <shell:ApplicationBarMenuItem Text="new" Click="New_Click"/>
      <shell:ApplicationBarMenuItem Text="open" Click="Open_Click"/>
      <shell:ApplicationBarMenuItem Text="save" Click="Save_Click"/>
    </shell:ApplicationBar.MenuItems>
  </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

See below:

ApplicationBar Menu XAML

Step 5

Then from the Windows Phone Controls section in the Toolbox select the TextBox control:

TextBox Control

Step 6

Draw a TextBox on the Page, below the Page Title, and in the XAML Pane between the <Grid x:Name="ContentGrid" Grid.Row="1"> and </Grid> lines, change "TextBox1" to the following:

<TextBox AcceptsReturn="True" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" FontSize="24" Name="Editor"/> 

See below:

MainPage with Editor TextBox

Step 7

Select Project then "Add New Item...", and select the "Windows Phone Portrait Page" Template, then change the "Name" to OpenPage.xaml, see below:

OpenPage Windows Phone Portrait Page

Step 8

In the Designer View for OpenPage.xaml, in the XAML Pane between between the <Grid Grid.Row="1" x:Name="ContentGrid"> and </Grid> lines type the following XAML:

<Grid x:Name="ContentMain">
  <Grid.RowDefinitions>
    <RowDefinition Height="*"/>
    <RowDefinition Height="Auto"/>
  </Grid.RowDefinitions>
  <!-- Content -->
  <ListBox Grid.Row="0" Margin="10" FontSize="48" Name="Files"/>
  <Grid Grid.Row="1" x:Name="Buttons" >
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="160"/>
      <ColumnDefinition Width="160"/>
      <ColumnDefinition Width="160"/>
    </Grid.ColumnDefinitions>
    <!-- Buttons -->
    <Button Grid.Column="0" Content="open" Click="Open_Click"/>
    <Button Grid.Column="1" Content="delete" Click="Delete_Click"/>
    <Button Grid.Column="2" Content="cancel" Click="Cancel_Click"/>
  </Grid>
</Grid>

XAML:

OpenPage XAML Pane

Design:

OpenPage Design View

Step 9

Right Click on the Page or the entry for "OpenPage.xaml" in Solution Explorer and choose the "View Code" option. In the Code View above "namespace TextEditor" type the following:

using System.IO.IsolatedStorage;

Also in the CodeView above "public OpenPage()" type the following Application declaration:

public App app = (App)Application.Current;

See Below:

OpenPage Includes and Application Declaration

Step 10

While still in the Code View for OpenPage.xaml.cs in the "public OpenPage()" Constructor below "InitializeComponent();" type the following:

ApplicationTitle.Text = "TEXT EDITOR";
PageTitle.Text = "open";
Loaded += (object sender, RoutedEventArgs e) =>
  {
    Files.Items.Clear();
    using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
    {
      foreach (string filename in storage.GetFileNames("*.txt"))
      {
        Files.Items.Add(filename.ToLower());
      }
    }
  };

See Below:

OpenPage Constructor

Step 11

While still in the Code View for OpenPage.xaml.cs, below the "}" of the "public OpenPage()" method type the following Event Handlers

private void Open_Click(object sender, RoutedEventArgs e)
{
  if (Files.SelectedItem != null)
  {
    app.Filename = (string)Files.SelectedItem;
    using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
    {
      IsolatedStorageFileStream location = new IsolatedStorageFileStream(app.Filename, 
        System.IO.FileMode.Open, storage);
      System.IO.StreamReader file = new System.IO.StreamReader(location);
      app.Content = file.ReadToEnd();
      file.Dispose();
      location.Dispose();
    }
    NavigationService.GoBack();
  }
}
 
private void Delete_Click(object sender, RoutedEventArgs e)
{
  if (Files.SelectedItem != null)
  {
    string _selected = (string)Files.SelectedItem;
    if (MessageBox.Show("Delete selected Document " + _selected + "?", "Text Editor",
      MessageBoxButton.OKCancel) == MessageBoxResult.OK)
    {
      using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
      {
        if (storage.FileExists(_selected))
        {
          storage.DeleteFile(_selected);
        }
      }
      NavigationService.GoBack();
    }
  }
}

private void Cancel_Click(object sender, RoutedEventArgs e)
{
  NavigationService.GoBack();
}

See Below:

OpenPage Event Handlers

Step 12

Select Project then "Add New Item...", and select the "Windows Phone Portrait Page" Template, then change the "Name" to SavePage.xaml, see below:

SavePage Windows Phone Portrait Page

Step 13

In the Designer View for SavePage.xaml, in the XAML Pane between between the <Grid Grid.Row="1" x:Name="ContentGrid"> and </Grid> lines type the following XAML:

<Grid x:Name="ContentMain">
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto"/>
    <RowDefinition Height="*"/>
    <RowDefinition Height="Auto"/>
  </Grid.RowDefinitions>
  <!-- Content -->
  <TextBox Grid.Row="0" FontSize="24" Name="Filename">
    <TextBox.InputScope>
      <InputScope>
        <InputScopeName NameValue="FileName"/>
      </InputScope>
    </TextBox.InputScope>
  </TextBox>
  <Grid Grid.Row="2" x:Name="Buttons" >
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="160"/>
      <ColumnDefinition Width="160"/>
      <ColumnDefinition Width="160"/>
    </Grid.ColumnDefinitions>
    <!-- Buttons -->
    <Button Grid.Column="0" Content="save" Click="Save_Click"/>
    <Button Grid.Column="2" Content="cancel" Click="Cancel_Click"/>
  </Grid>
</Grid>

XAML:

SavePage XAML Pane

Design:

OpenPage Design View

Step 14

Right Click on the Page or the entry for "SavePage.xaml" in Solution Explorer and choose the "View Code" option. In the Code View above "namespace TextEditor" type the following:

using System.IO.IsolatedStorage;

Also in the CodeView above "public SavePage()" type the following Application declaration:

public App app = (App)Application.Current;

See Below:

SavePage Includes and Application Declaration

Step 15

While still in the Code View for SavePage.xaml.cs in the "public SavePage()" Constructor below "InitializeComponent();" type the following:

ApplicationTitle.Text = "TEXT EDITOR";
PageTitle.Text = "save";
Loaded += (object sender, RoutedEventArgs e) =>
  {
    if (app.Filename == "")
    {
      Filename.Text = "untitled.txt";
    }
      else
    {
      Filename.Text = app.Filename;
    }
  };

See Below:

SavePage Constructor

Step 16

While still in the Code View for SavePage.xaml.cs, below the "}" of the "public SavePage()" method type the following Event Handlers

private void Save_Click(object sender, RoutedEventArgs e)
{
  if (Filename.Text != "")
  {
    try
    {
      app.Filename = Filename.Text.Trim().ToLower();
      using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
      {
        IsolatedStorageFileStream location = new IsolatedStorageFileStream(app.Filename, 
        System.IO.FileMode.Create, storage);
        System.IO.StreamWriter file = new System.IO.StreamWriter(location);
        file.Write(app.Content);
        file.Dispose();
        location.Dispose();
      }
    NavigationService.GoBack();
    }
    catch
    {
      // Ignore Errors
    }
  }
}
 
private void Cancel_Click(object sender, RoutedEventArgs e)
{
  NavigationService.GoBack();
}

See Below:

SavePage Event Handlers

Step 17

Right Click on the Page or the entry for "MainPage.xaml" in Solution Explorer and choose the "View Code" option. In the Code View above "public MainPage()" type the following Application declaration:

public App app = (App)Application.Current;

See Below:

MainPage Application Declaration

Step 18

While still in the Code View for MainPage.xaml.cs in the "public MainPage()" Constructor below "InitializeComponent();" type or replace with the following:

ApplicationTitle.Text = "TEXT EDITOR";
PageTitle.Text = "untitled.txt";
Loaded += (object sender, RoutedEventArgs e) =>
  {
    if (app.Content != null)
    {
      Editor.Text = (string)app.Content;
    }
    if (app.Filename != "")
    {
      PageTitle.Text = app.Filename;
    }
    else
    {
      PageTitle.Text = "untitled.txt";
    }
  };

See Below:

MainPage Constructor

Step 19

While still in the Code View for MainPage.xaml.cs, below the "}" of the "public MainPage()" method type the following Helper Method and Event Handlers:

private void New_Click(object sender, EventArgs e)
{
  if (MessageBox.Show("Start a new Document?", "Text Editor",
  MessageBoxButton.OKCancel) == MessageBoxResult.OK)
  {
    PageTitle.Text = "untitled.txt";
    Editor.Text = "";
    app.Filename = PageTitle.Text;
    app.Content = Editor.Text;
  }
}

private void Open_Click(object sender, EventArgs e)
{
  app.Content = Editor.Text;
  NavigationService.Navigate(new Uri("/OpenPage.xaml", UriKind.Relative));
}

private void Save_Click(object sender, EventArgs e)
{
  app.Content = Editor.Text;
  NavigationService.Navigate(new Uri("/SavePage.xaml", UriKind.Relative));
}

See Below:

MainPage Event Handlers

Step 20

Save the Project as you have now finished the Windows Phone Silverlight application. Select the Windows Phone Emulator option then Select Debug then Start Debugging or click on Start Debugging:

Start Debugging

After you do, the following will appear in the Windows Phone Emulator after it has been loaded:

Application Running

Step 21

If you select the TextBox - you can then begin typing a new Document, then if you want to Save this - click on the "..." on the menu then choose "save" enter a filename and click "save" to save the document and return to the main screen, you can then use Open to open this later, see below:

Text Editor

Step 22

You can then Stop the application by selecting the Visual Studio 2010 application window and clicking on the Stop Debugging button:

Stop Debugging

This is a Simple Text Editing application with the ability to Open and Save Text Files using a Windows Phone 7 Silverlight Application. You can try adding your own features such as the ablity to change the font size and more - make it your own!

Share

Creative Commons License

Copyright Comentsys © 2009 - 2010, All rights reserved. About | Contact | Link to Page
Valid XHTML 1.1! Valid CSS Level Double-A conformance icon, W3C-WAI Web Content Accessibility Guidelines 1.0 This website is ICRA rated Creative Commons License