Universal Windows Platform – Task Editor

Task Editor demonstrates how to use a ListBox to create a todo-list style application where you can Load and Save tasks

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.Collections.ObjectModel;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;

[DataContract]
public class Task
{
    [DataMember]
    public bool Done { get; set; }

    [DataMember]
    public string Text { get; set; }
}

public class Library
{
    private const string app_title = "Task Editor";
    private const string file_extension = ".tsk";

    private ObservableCollection<Task> _list = new ObservableCollection<Task>();
    DataContractJsonSerializer _serialiser = new DataContractJsonSerializer(typeof(ObservableCollection<Task>));

    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;
    }

    public void Add(ref ListBox display, string value, KeyRoutedEventArgs args)
    {
        if (args.Key == Windows.System.VirtualKey.Enter)
        {
            if (display.SelectedIndex > -1)
            {
                _list.Insert(display.SelectedIndex,
                    new Task() { Text = value }); // Insert at Selected
            }
            else
            {
                _list.Add(new Task() { Text = value }); // Add at End
            }
            display.ItemsSource = _list;
            display.Focus(FocusState.Keyboard);
        }
    }

    public void Remove(ref ListBox display)
    {
        if (display.SelectedIndex > -1)
        {
            _list.RemoveAt(display.SelectedIndex);
            display.ItemsSource = _list;
        }
    }

    public async void New(ListBox display)
    {
        if (await ConfirmAsync("Create New List?", app_title, "Yes", "No"))
        {
            _list.Clear();
            display.ItemsSource = _list;
            display.Focus(FocusState.Keyboard);
        }
    }

    public async void OpenAsync(ListBox display)
    {
        try
        {
            FileOpenPicker picker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };
            picker.FileTypeFilter.Add(file_extension);
            StorageFile file = await picker.PickSingleFileAsync();
            if (file != null)
            {
                _list = (ObservableCollection<Task>)
                    _serialiser.ReadObject(await file.OpenStreamForReadAsync());
                display.ItemsSource = _list;
            }
        }
        catch
        {

        }
    }

    public async void SaveAsync(ListBox display)
    {
        try
        {
            FileSavePicker picker = new FileSavePicker
            {
                DefaultFileExtension = file_extension,
                SuggestedFileName = "Tasks",
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };
            picker.FileTypeChoices.Add("Task List", new List<string>() { file_extension });

            StorageFile file = await picker.PickSaveFileAsync();
            if (file != null)
            {
                _serialiser.WriteObject(await file.OpenStreamForWriteAsync(), _list);
            }
        }
        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 task list is to be created, if the answer is “Yes” then the ListBox will have it’s contents set to a cleared List. Add will put items into an ObservableCollection either at the SelectedIndex of the ListBox or it will put them at the end of the ObservableCollection. Remove will remove any items from the ObservableCollection at the SelectedIndex position of the ListBox. OpenAsync is used to set the ObservableCollection contents to the contents of a file – this is opened with a FileOpenPicker using the DataContractJsonSerializer and OpenStreamForReadAsync which is then databound to the ListBox, SaveAsync is used to get the contents of the ObservableCollection and then this is saved to a file, using the FileSavePicker and OpenStreamForWriteAsync.

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="*"/>
	</Grid.RowDefinitions>
	<TextBox Grid.Row="0" Margin="20" KeyDown="Add_KeyDown" Name="Value"/>
	<ListBox Grid.Row="1" FontFamily="Segoe UI" FontSize="16" Name="Display">
		<ListBox.ItemTemplate>
			<DataTemplate>
				<CheckBox IsChecked="{Binding Done, Mode=TwoWay}" Content="{Binding Text}"/>
			</DataTemplate>
		</ListBox.ItemTemplate>
	</ListBox>
</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"/>
	<AppBarButton Name="Remove" Icon="Remove" Label="Remove" Click="Remove_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Application, this features a Grid with a TextBox on the first row. The second row has the ListBox that will be where the todo-list will appear as a set of CheckBox controls. The second block of XAML is is the CommandBar which contains the New, Open and Save commands to perform the actions of the Task Editor using the ListBox and TextBox.

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 Add_KeyDown(object sender, KeyRoutedEventArgs e)
{
	library.Add(ref Display, Value.Text, e);
}

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

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

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

private void Remove_Click(object sender, RoutedEventArgs e)
{
	library.Remove(ref Display);
}

Below the MainPage() Method an instance of the Library Class is created. The Add_KeyDown Event handles the addition of tasks to the list. The New_Click, Open_Click, Save_Click and Remove_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 some text in the upper textbox then press or tap enter to add a Task then you can Save the list to Open later or start a New list you can also tick the checkbox when the Task is done

ran-task-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