Universal Windows Platform – Rich Editor

Rich Editor demonstrates how to use a RichEditBox to open and save rich text documents

Step 1

If not already, follow Setup and Start on how to Install and get Started with Visual Studio 2017 or in Windows 10 choose Start, and then from the Start Menu find and select Visual Studio 2017.

vs2017

Step 2

Once Visual Studio Community 2017 has started, from the Menu choose File, then New then Project…

vs2017-file-new-project

Step 3

From New Project choose Visual C# from Installed, Templates then choose Blank App (Universal Windows) and then type in a Name and select a Location and then select Ok to create the Project
vs2017-new-project-window

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

The Target Version will control what features your application can use in Windows 10 so by picking the most recent version you’ll be able to take advantage of those features. To make sure you always have the most recent version, in Visual Studio 2017 select Tools Extensions and Updates… then and then see if there are any Updates

Step 5

Once done select from the Menu, Project, then Add New Item…

vs2017-project-add-new-item

Step 6

From the Add New Item window select Visual C#, then Code from Installed then select Code File from the list, then type in the Name as Library.cs before selecting Add to add the file to the Project

vs2017-add-new-item-library

Step 7

Once in the Code View for Library.cs the following should be entered:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

public class Library
{
    private const string app_title = "Rich Editor";
    private const string file_extension = ".rtf";

    public async Task<bool> ConfirmAsync(string content, string title, string ok, string cancel)
    {
        bool result = false;
        MessageDialog dialog = new MessageDialog(content, title);
        dialog.Commands.Add(new UICommand(ok, new UICommandInvokedHandler((cmd) => result = true)));
        dialog.Commands.Add(new UICommand(cancel, new UICommandInvokedHandler((cmd) => result = false)));
        await dialog.ShowAsync();
        return result;
    }

    private void Focus(ref RichEditBox display)
    {
        display.Focus(FocusState.Keyboard);
    }

    private void Set(ref RichEditBox display, string value)
    {
        display.Document.SetText(TextSetOptions.FormatRtf, value);
        Focus(ref display);
    }

    public string Get(ref RichEditBox display)
    {
        string value = string.Empty;
        display.Document.GetText(TextGetOptions.FormatRtf, out value);
        return value;
    }

    public bool Bold(ref RichEditBox display)
    {
        display.Document.Selection.CharacterFormat.Bold = FormatEffect.Toggle;
        Focus(ref display);
        return display.Document.Selection.CharacterFormat.Bold.Equals(FormatEffect.On);
    }

    public bool Italic(ref RichEditBox display)
    {
        display.Document.Selection.CharacterFormat.Italic = FormatEffect.Toggle;
        Focus(ref display);
        return display.Document.Selection.CharacterFormat.Italic.Equals(FormatEffect.On);
    }

    public bool Underline(ref RichEditBox display)
    {
        display.Document.Selection.CharacterFormat.Underline =
            display.Document.Selection.CharacterFormat.Underline.Equals(UnderlineType.Single) ?
            UnderlineType.None : UnderlineType.Single;
        display.Document.Selection.CharacterFormat.Italic = FormatEffect.Toggle;
        Focus(ref display);
        return display.Document.Selection.CharacterFormat.Underline.Equals(UnderlineType.Single);
    }

    public bool Align(ref RichEditBox display, ParagraphAlignment alignment)
    {
        display.Document.Selection.ParagraphFormat.Alignment = alignment;
        Focus(ref display);
        return display.Document.Selection.ParagraphFormat.Alignment.Equals(alignment);
    }

    public void Size(ref RichEditBox display, ref ComboBox value)
    {
        if (display != null && value != null)
        {
            string selected = ((ComboBoxItem)value.SelectedItem).Tag.ToString();
            display.Document.Selection.CharacterFormat.Size = float.Parse(selected);
            Focus(ref display);
        }
    }

    public void Colour(ref RichEditBox display, ref ComboBox value)
    {
        if (display != null && value != null)
        {
            string selected = ((ComboBoxItem)value.SelectedItem).Tag.ToString();
            display.Document.Selection.CharacterFormat.ForegroundColor = Color.FromArgb(
                Byte.Parse(selected.Substring(0, 2), NumberStyles.HexNumber),
                Byte.Parse(selected.Substring(2, 2), NumberStyles.HexNumber),
                Byte.Parse(selected.Substring(4, 2), NumberStyles.HexNumber),
                Byte.Parse(selected.Substring(6, 2), NumberStyles.HexNumber));
            Focus(ref display);
        }
    }

    public async void NewAsync(RichEditBox display)
    {
        if (await ConfirmAsync("Create New Document?", app_title, "Yes", "No"))
        {
            Set(ref display, string.Empty);
        }
    }

    public async void OpenAsync(RichEditBox display)
    {
        try
        {
            FileOpenPicker picker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };
            picker.FileTypeFilter.Add(file_extension);
            StorageFile file = await picker.PickSingleFileAsync();
            Set(ref display, await FileIO.ReadTextAsync(file));
        }
        catch
        {

        }
    }

    public async void SaveAsync(RichEditBox display)
    {
        try
        {
            FileSavePicker picker = new FileSavePicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
                DefaultFileExtension = file_extension,
                SuggestedFileName = "Document"
            };
            picker.FileTypeChoices.Add("Rich Text", new List<string>() { file_extension });
            StorageFile file = await picker.PickSaveFileAsync();
            if (file != null)
            {
                await FileIO.WriteTextAsync(file, Get(ref display));
            }
        }
        catch
        {

        }
    }
}

In the Library.cs there are using statements to include the necessary functionality. The ConfirmAsync Method is used to create a dialog with two buttons, this is used by the NewAsync method to confirm if a new document is to be created, if the answer is “Yes” then the TextBox will have it’s contents set to an empty string. OpenAsync is used to set the TextBox contents to the contents of a file – this is opened with a FileOpenPicker using ReadTextAsync, SaveAsync is used to get the contents of the TextBox and then this is saved to a file, using the FileSavePicker and WriteTextAsync.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage

Step 9

From the Menu choose View and then Designer

vs2017-view-designer

Step 10

The Design View will be displayed along with the XAML View and in this between the Grid and /Grid elements, enter the following XAML:

<Grid>
	<Grid.RowDefinitions>
		<RowDefinition Height="Auto"/>
		<RowDefinition Height="Auto"/>
		<RowDefinition Height="*"/>
	</Grid.RowDefinitions>
	<StackPanel Grid.Row="0" Orientation="Horizontal">
		<AppBarToggleButton Name="Bold" Icon="Bold" Label="Bold" Click="Bold_Click"/>
		<AppBarToggleButton Name="Italic" Icon="Italic" Label="Italic" Click="Italic_Click"/>
		<AppBarToggleButton Name="Underline" Icon="Underline" Label="Underline" Click="Underline_Click"/>
		<ComboBox Name="Size" VerticalAlignment="Center" SelectionChanged="Size_SelectionChanged">
			<ComboBoxItem Content="8" Tag="8"/>
			<ComboBoxItem Content="10" Tag="10"/>
			<ComboBoxItem Content="12" Tag="12"/>
			<ComboBoxItem Content="16" Tag="16" IsSelected="True"/>
			<ComboBoxItem Content="20" Tag="20"/>
			<ComboBoxItem Content="24" Tag="24"/>
			<ComboBoxItem Content="28" Tag="28"/>
			<ComboBoxItem Content="36" Tag="36"/>
			<ComboBoxItem Content="48" Tag="48"/>
			<ComboBoxItem Content="72" Tag="72"/>
		</ComboBox>
	</StackPanel>
	<StackPanel Grid.Row="1" Orientation="Horizontal">
		<AppBarToggleButton Name="Left" Icon="AlignLeft" Label="Left" Click="Left_Click"/>
		<AppBarToggleButton Name="Centre" Icon="AlignCenter" Label="Centre" Click="Centre_Click"/>
		<AppBarToggleButton Name="Right" Icon="AlignRight" Label="Right" Click="Right_Click"/>
		<ComboBox Name="Colour" VerticalAlignment="Center" SelectionChanged="Colour_SelectionChanged">
			<ComboBoxItem Tag="FF000000" IsSelected="True">
				<Rectangle Width="25" Height="14" Fill="Black"/>
			</ComboBoxItem>
			<ComboBoxItem Tag="FF808080">
				<Rectangle Width="25" Height="14" Fill="Gray"/>
			</ComboBoxItem>
			<ComboBoxItem Tag="FFFF0000">
				<Rectangle Width="25" Height="14" Fill="Red"/>
			</ComboBoxItem>
			<ComboBoxItem Tag="FFFFA500">
				<Rectangle Width="25" Height="14" Fill="Orange"/>
			</ComboBoxItem>
			<ComboBoxItem Tag="FFFFFF00">
				<Rectangle Width="25" Height="14" Fill="Yellow"/>
			</ComboBoxItem>
			<ComboBoxItem Tag="FF008000">
				<Rectangle Width="25" Height="14" Fill="Green"/>
			</ComboBoxItem>
			<ComboBoxItem Tag="FF00FFFF">
				<Rectangle Width="25" Height="14" Fill="Cyan"/>
			</ComboBoxItem>
			<ComboBoxItem Tag="FF0000FF">
				<Rectangle Width="25" Height="14" Fill="Blue"/>
			</ComboBoxItem>
			<ComboBoxItem Tag="FFFF00FF">
				<Rectangle Width="25" Height="14" Fill="Magenta"/>
			</ComboBoxItem>
			<ComboBoxItem Tag="FF800080">
				<Rectangle Width="25" Height="14" Fill="Purple"/>
			</ComboBoxItem>
		</ComboBox>
	</StackPanel>
	<RichEditBox Grid.Row="2" AcceptsReturn="True" TextWrapping="Wrap" VerticalAlignment="Stretch" FontFamily="Segoe UI" FontSize="16" Name="Display"/>
</Grid>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Name="New" Icon="Page2" Label="New" Click="New_Click"/>
	<AppBarButton Name="Open" Icon="OpenFile" Label="Open" Click="Open_Click"/>
	<AppBarButton Name="Save" Icon="Save" Label="Save" Click="Save_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Application, this features a Grid with a StackPanel on the first row with commands for Bold, Italic and Underline buttons with a ComboBox with values for font sizes. The second row has another StackPanel with Left, Centre and Right buttons with a ComboBox with values for font colours. The third row has the RichEditBox that will be set with the commands. The second block of XAML is is the CommandBar which contains the New, Open and Save commands to perform the actions of the Rich Editor using the RichEditBox.

Step 11

From the Menu choose View and then Code

vs2017-view-code

Step 12

Once in the Code View, below the end of public MainPage() { … } the following Code should be entered:

Library library = new Library();

private void Bold_Click(object sender, RoutedEventArgs e)
{
	Bold.IsChecked = library.Bold(ref Display);
}

private void Italic_Click(object sender, RoutedEventArgs e)
{
	Italic.IsChecked = library.Italic(ref Display);
}

private void Underline_Click(object sender, RoutedEventArgs e)
{
	Underline.IsChecked = library.Underline(ref Display);
}

private void Left_Click(object sender, RoutedEventArgs e)
{
	Left.IsChecked = library.Align(ref Display, 
		Windows.UI.Text.ParagraphAlignment.Left);
	Centre.IsChecked = false;
	Right.IsChecked = false;
}

private void Centre_Click(object sender, RoutedEventArgs e)
{
	Left.IsChecked = false;
	Centre.IsChecked = library.Align(ref Display,
		Windows.UI.Text.ParagraphAlignment.Center);
	Right.IsChecked = false;
}

private void Right_Click(object sender, RoutedEventArgs e)
{
	Left.IsChecked = false;
	Centre.IsChecked = false;
	Right.IsChecked = library.Align(ref Display,  
		Windows.UI.Text.ParagraphAlignment.Right);
}

private void Size_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
	library.Size(ref Display, ref Size);
}

private void Colour_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
	library.Colour(ref Display, ref Colour);
}

private void New_Click(object sender, RoutedEventArgs e)
{
	library.NewAsync(Display);
}

private void Open_Click(object sender, RoutedEventArgs e)
{
	library.OpenAsync(Display);
}

private void Save_Click(object sender, RoutedEventArgs e)
{
	library.SaveAsync(Display);
}

Below the MainPage() Method an instance of the Library Class is created. The New_Click, Open_Click and Save_Click Methods call the related methods in the Library Class.

Step 13

That completes the Universal Windows Platform Application so Save the Project then in Visual Studio select the Local Machine to run the Application

vs2017-local-machine

Step 14

After the Application has started running you can then type in any text then you can Save the document to Open later or start a New document you can also make text Bold, Italic, Underline change the text alignment, font size and colour

ran-rich-editor

Step 15

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s