Universal Windows Platform – Tutorials

Setup and Start
Setup and Start
Input Dialog
Custom Dialog
Access Keys
Access Keys
Light Effect
Light Effect
Shade Effect
Shade Effect
Lucky Dominoes
Lucky Dominoes
Lucky Roshambo
Lucky Roshambo
Deal or Not
Deal or Not
High or Low
High or Low
Codes Game
Codes Game
Flags Game
Flags Game
Order Game
Chase Game
Slide Game
Slide Game
GifView App
GifView App
PdfView App
PdfView App
JpgInfo App
JpgInfo App
ZipFile App
ZipFile App
Operator App
Operator App
Speaking App
Speaking App
Calendar App
Calendar App
Contacts App
Contacts App
Custom TextBox
Custom TextBox
Custom ComboBox
Custom ComboBox
Matrix Control
Matrix Control
Lights Control
Lights Control
Stacked Control
Stacked Control
Directs Control
Directs Control
Uniform Control
Uniform Control
Docking Control
Docking Control
Badges
Badges
Tile Output
Tile Styles
Toast Styles
Toast Styles
Database
Database
Source Code
Source Code

May 2016

Custom Dialog
Custom Dialog
Hamburger Menu
Hamburger Menu
Drag and Drop
Drag and Drop
Photo Rotate
Photo Rotate
Lucky Roulette
Lucky Roulette
Lucky Bingo
Lucky Bingo
Hit or Miss
Hit or Miss
Four in Row
Four in Row
Fruit Game
Fruit Game
Light Game
Light Game
Order Game
Order Game
Sound Game
Sound Game
Appointment App
Appointment App
Cryptograph App
Cryptograph App
Compression App
Compression App
Recognition App
Recognition App
Tailored App
Tailored App
Adaptive App
Adaptive App
Keyboard App
Keyboard App
Jsonfile App
Jsonfile App
Custom Checkbox
Custom Checkbox
Custom Toggle
Custom Toggle
Digital Control
Digital Control
Radial Control
Radial Control
Offset Control
Offset Control
Gauge Control
Gauge Control
Font Control
Font Control
Colour Control
Colour Control
Cortana
Cortana
Tile Output
Tile Output
Toast Input
Toast Input
Groove
Groove
Source Code
Source Code

May 2015

Hello World
Hello World
Application Bar
Application Bar
Data Input
Data Input
Image Rotate
Image Rotate
Lucky Dice
Lucky Dice
Lucky Lotto
Lucky Lotto
Noughts and Crosses
Noughts and Crosses
Memory Game
Memory Game
Touch Game
Touch Game
Playing Cards
Playing Cards
Web Browser
Web Browser
RSS Reader
RSS Reader
Text Editor
Text Editor
Rich Editor
Rich Editor
Task Editor
Task Editor
Draw Editor
Draw Editor
Slide Player
Slide Player
Media Player
Media Player
Audio Recorder
Audio Recorder
Video Recorder
Video Recorder
Custom Button
Custom Button
Custom Slider
Custom Slider
Clock Control
Clock Control
Carousel Control
Carousel Control
Wrap Control
Wrap Control
Dial Control
Dial Control
Flip Control
Flip Control
Carousel Control
Expand Control
Location
Location
Tiles
Tiles
Toasts
Toasts
Agent
Agent
Source Code
Source Code
Advertisements

Universal Windows Platform – Database

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 locate and select Visual Studio 2017.

vs2017-home

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 the Name as Database and select a Location and then select Ok to create the Project

vs2017-new-project

Step 4

Then in New Universal Windows Project you need to select the Target Version to be Windows 10 Creators Update (10.0; Build 15063) and the Minimum Version to be at least Windows 10 Anniversary Update (10.0; Build 14393) or Windows 10 Creators Update (10.0; Build 15063)

vs2017-platform

Step 5

From the Menu choose Tools, then NuGet Package Manager and Manage NuGet Packages for Solution…

vs2017-manage-nuget

Step 6

Then in NuGet select Browse and search for Microsoft.Data.SQLite as indicated and select Microsoft.Data.SQLite by Microsoft and then check the box under Project as indicated and select Install.

nuget-database

Step 7

Then if Preview for Review Changes is displayed, select Ok

nuget-review-database

Step 8

License Acceptance will then be displayed, read through the terms displayed then to continue, select I Accept to install the package.

nuget-license-database

Step 9

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 10

From the Add New Item choose Visual C# from Installed then choose Code then select Code File and then in the Name as Library.cs and then select Add to add the file to the Project

vs2017-library

Step 11

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

using Microsoft.Data.Sqlite;
using Microsoft.Data.Sqlite.Internal;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

public class Item
{
    public int Id { get; set; }
    public string Album { get; set; }
    public string Artist { get; set; }
    public string Genre { get; set; }
}

public class Library
{
    private const string field_id = "@Id";
    private const string field_album = "@Album";
    private const string field_artist = "@Artist";
    private const string field_genre = "@Genre";
    private const string connection_string = "Filename=database.db";
    private const string table_create = "CREATE TABLE IF NOT EXISTS Items " +
        "(Id INTEGER PRIMARY KEY AUTOINCREMENT, " +
        "Album NVARCHAR(255) NULL, Artist NVARCHAR(255) NULL, Genre NVARCHAR(255) NULL)";
    private const string table_insert = "INSERT INTO Items VALUES (NULL, @Album, @Artist, @Genre)";
    private const string table_update = "UPDATE Items SET Album = @Album, " +
        "Artist = @Artist, Genre = @Genre WHERE Id = @Id";
    private const string table_delete = "DELETE FROM Items WHERE Id = @Id";
    private const string table_select = "SELECT Id, Album, Artist, Genre FROM Items";

    private async Task<Item> Dialog(Item item)
    {
        Thickness margin = new Thickness(5);
        TextBlock id = new TextBlock()
        {
            Text = item.Id.ToString(),
            Margin = margin,
        };
        TextBox album = new TextBox()
        {
            Text = item.Album ?? string.Empty,
            Margin = margin,
            PlaceholderText = "Album"
        };
        TextBox artist = new TextBox()
        {
            Text = item.Artist ?? string.Empty,
            Margin = margin,
            PlaceholderText = "Artist"
        };
        TextBox genre = new TextBox()
        {
            Text = item.Genre ?? string.Empty,
            Margin = margin,
            PlaceholderText = "Genre"
        };
        StackPanel panel = new StackPanel()
        {
            Orientation = Orientation.Vertical
        };
        panel.Children.Add(id);
        panel.Children.Add(album);
        panel.Children.Add(artist);
        panel.Children.Add(genre);
        ContentDialog dialog = new ContentDialog()
        {
            Title = "Database",
            PrimaryButtonText = "Save",
            CloseButtonText = "Cancel",
            Content = panel
        };
        ContentDialogResult result = await dialog.ShowAsync();
        if (result == ContentDialogResult.Primary)
        {
            item.Album = album.Text;
            item.Artist = artist.Text;
            item.Genre = genre.Text;
            return item;
        }
        return null;
    }

    private async Task<bool> AddItemAsync(Item item)
    {
        bool result = false;
        using (SqliteConnection connection = new SqliteConnection(connection_string))
        {
            await connection.OpenAsync();
            SqliteCommand insert = new SqliteCommand()
            {
                Connection = connection,
                CommandText = table_insert
            };
            insert.Parameters.AddWithValue(field_album, item.Album);
            insert.Parameters.AddWithValue(field_artist, item.Artist);
            insert.Parameters.AddWithValue(field_genre, item.Genre);
            try
            {
                await insert.ExecuteScalarAsync();
                result = true;
            }
            catch (SqliteException)
            {
                result = false;
            }
            connection.Close();
        }
        return result;
    }

    private async Task<bool> EditItemAsync(Item item)
    {
        bool result = false;
        using (SqliteConnection connection = new SqliteConnection(connection_string))
        {
            await connection.OpenAsync();
            SqliteCommand insert = new SqliteCommand()
            {
                Connection = connection,
                CommandText = table_update
            };
            insert.Parameters.AddWithValue(field_id, item.Id);
            insert.Parameters.AddWithValue(field_album, item.Album);
            insert.Parameters.AddWithValue(field_artist, item.Artist);
            insert.Parameters.AddWithValue(field_genre, item.Genre);
            try
            {
                await insert.ExecuteScalarAsync();
                result = true;
            }
            catch (SqliteException)
            {
                result = false;
            }
            connection.Close();
        }
        return result;
    }

    private async Task<bool> DeleteItemAsync(Item item)
    {
        bool result = false;
        using (SqliteConnection connection = new SqliteConnection(connection_string))
        {
            await connection.OpenAsync();
            SqliteCommand delete = new SqliteCommand()
            {
                Connection = connection,
                CommandText = table_delete
            };
            delete.Parameters.AddWithValue(field_id, item.Id);
            try
            {
                await delete.ExecuteNonQueryAsync();
                result = true;
            }
            catch (SqliteException)
            {
                result = false;
            }
            connection.Close();
        }
        return result;
    }

    public async Task<bool> CreateAsync()
    {
        bool result = false;
        SqliteEngine.UseWinSqlite3();
        using (SqliteConnection connection = new SqliteConnection(connection_string))
        {
            await connection.OpenAsync();
            SqliteCommand create = new SqliteCommand(table_create, connection);
            try
            {
                await create.ExecuteNonQueryAsync();
                result = true;
            }
            catch (SqliteException)
            {
                result = false;
            }
            connection.Close();
        }
        return result;
    }

    public async Task<List<Item>> ListAsync()
    {
        List<Item> results = new List<Item>();
        using (SqliteConnection connection = new SqliteConnection(connection_string))
        {
            await connection.OpenAsync();
            SqliteCommand select = new SqliteCommand(table_select, connection);
            try
            {
                SqliteDataReader query = await select.ExecuteReaderAsync();
                while (query.Read())
                {
                    Item item = new Item()
                    {
                        Id = query.GetInt32(0),
                        Album = query.GetString(1),
                        Artist = query.GetString(2),
                        Genre = query.GetString(3)
                    };
                    results.Add(item);
                }
            }
            catch (SqliteException)
            {
                results = null;
            }
            connection.Close();
        }
        return results;
    }

    public async Task<bool> AddAsync()
    {
        Item item = await Dialog(new Item());
        if (item != null)
        {
            return await AddItemAsync(item);
        }
        return false;
    }

    public async Task<bool> EditAsync(AppBarButton button)
    {
        Item item = await Dialog((Item)button.Tag);
        if(item != null)
        {
            return await EditItemAsync(item);
        }
        return false;
    }

    public async Task<bool> DeleteAsync(AppBarButton button)
    {
        Item item = (Item)button.Tag;
        if(item != null)
        {
            return await DeleteItemAsync(item);
        }
        return false;
    }
}

Step 12

Then in the Solution Explorer select MainPage.xaml

vs2017-library-mainpage

Step 13

From the Menu choose View and then Designer

vs2017-view-designer

Step 14

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.RowDefinitions>
	<RowDefinition Height="*"/>
	<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<CommandBar Grid.Row="1" VerticalAlignment="Bottom">
	<AppBarButton Name="Add" Icon="Add" Label="Add" Click="Add_Click"/>
</CommandBar>
<ListBox Grid.Row="0" Name="Display" Loaded="Display_Loaded">
	<ListBox.ItemContainerStyle>
		<Style TargetType="ListBoxItem">
			<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
		</Style>
	</ListBox.ItemContainerStyle>
	<ListBox.ItemTemplate>
		<DataTemplate>
			<Grid>
				<Grid.ColumnDefinitions>
					<ColumnDefinition Width="Auto"/>
					<ColumnDefinition Width="20*"/>
					<ColumnDefinition Width="20*"/>
					<ColumnDefinition Width="20*"/>
					<ColumnDefinition Width="Auto"/>
				</Grid.ColumnDefinitions>
				<Grid Padding="5" Grid.Column="0" Background="{ThemeResource AccentButtonBackground}">
					<TextBlock Text="{Binding Id}" VerticalAlignment="Center"
					Foreground="{ThemeResource AccentButtonForeground}"/>
				</Grid>
				<Grid Padding="5" Grid.Column="1" Background="{ThemeResource AccentButtonForeground}">
					<TextBlock Text="{Binding Album}" VerticalAlignment="Center"
					Foreground="{ThemeResource AccentButtonBackground}"/>
				</Grid>
				<Grid Padding="5" Grid.Column="2" Background="{ThemeResource AccentButtonForeground}">
					<TextBlock Text="{Binding Artist}" VerticalAlignment="Center"
					Foreground="{ThemeResource AccentButtonBackground}"/>
				</Grid>
				<Grid Padding="5" Grid.Column="3" Background="{ThemeResource AccentButtonForeground}">
					<TextBlock Text="{Binding Genre}" VerticalAlignment="Center"
					Foreground="{ThemeResource AccentButtonBackground}"/>
				</Grid>
				<StackPanel Grid.Column="4" Orientation="Horizontal">
					<AppBarButton Name="Edit" Icon="Edit" Label="Edit" Tag="{Binding}" Click="Edit_Click"/>
					<AppBarButton Name="Delete" Icon="Delete" Label="Delete" Tag="{Binding}" Click="Delete_Click"/>
				</StackPanel>
			</Grid>
		</DataTemplate>
	</ListBox.ItemTemplate>
</ListBox>

It should appear as such:

xaml-database

Step 15

From the Menu choose View and then Code

vs2017-view-code

Step 16

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

Library library = new Library();

private async void Display_Loaded(object sender, RoutedEventArgs e)
{
	await library.CreateAsync();
	Display.ItemsSource = await library.ListAsync();
}

private async void Add_Click(object sender, RoutedEventArgs e)
{
	if (await library.AddAsync())
	{
		Display.ItemsSource = await library.ListAsync();
	}
}

private async void Edit_Click(object sender, RoutedEventArgs e)
{
	if (await library.EditAsync((AppBarButton)sender))
	{
		Display.ItemsSource = await library.ListAsync();
	}
}

private async void Delete_Click(object sender, RoutedEventArgs e)
{
	if (await library.DeleteAsync((AppBarButton)sender))
	{
		Display.ItemsSource = await library.ListAsync();
	}
}

It should then appear as such:

code-database

Step 17

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

vs2017-debug

Step 18

Once started the Application should then appear

run-database

Step 19

After the Application has started running you can then select Add to create a new Item, this will display a Dialog where you can enter the Album, Artist and Genra. Items added will be displayed in the List where you can Edit or Delete them.

ran-database

Step 20

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Universal Windows Platform – Toast Styles

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 locate and select Visual Studio 2017.

vs2017-home

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

Step 4

Then in New Universal Windows Project you need to select the Target Version to be Windows 10 Creators Update (10.0; Build 15063) and the Minimum Version to be at least Windows 10 Anniversary Update (10.0; Build 14393) or Windows 10 Creators Update (10.0; Build 15063)

vs2017-platform

Step 5

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 6

From the Add New Item choose Visual C# from Installed then choose Code then select Code File and then in the Name as Library.cs and then select Add to add the file to the Project

vs2017-library

Step 7

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

public class Library
{
    public IEnumerable<string> GetTemplates()
    {
        return Enum.GetValues(typeof(ToastTemplateType))
            .Cast<ToastTemplateType>().Select(s => s.ToString());
    }

    private void UpdateToast(string style, string value)
    {
        ToastTemplateType template = (ToastTemplateType)Enum.Parse(typeof(ToastTemplateType), style);
        XmlDocument toast = ToastNotificationManager.GetTemplateContent(template);
        XmlNodeList text = toast.GetElementsByTagName("text");
        if (text.Length > 0)
        {
            text[0].AppendChild(toast.CreateTextNode(value));
        }
        XmlNodeList image = toast.GetElementsByTagName("image");
        if (image.Length > 0)
        {
            image[0].Attributes.GetNamedItem("src").NodeValue =
            "Assets/Square44x44Logo.scale-200.png";
        }
        ToastNotification notification = new ToastNotification(toast);
        ToastNotificationManager.CreateToastNotifier().Show(notification);
    }

    private async Task<Tuple<string, string>> Dialog()
    {
        ComboBox template = new ComboBox()
        {
            HorizontalAlignment = HorizontalAlignment.Stretch,
            Margin = new Thickness(5),
            ItemsSource = GetTemplates()
        };
        template.SelectedIndex = 0;
        TextBox text = new TextBox()
        {
            PlaceholderText = "Text",
            Margin = new Thickness(5)
        };
        StackPanel panel = new StackPanel()
        {
            Orientation = Orientation.Vertical
        };
        panel.Children.Add(template);
        panel.Children.Add(text);
        ContentDialog dialog = new ContentDialog()
        {
            Title = "Toast Styles",
            PrimaryButtonText = "Update",
            CloseButtonText = "Cancel",
            Content = panel
        };
        ContentDialogResult result = await dialog.ShowAsync();
        if (result == ContentDialogResult.Primary)
        {
            return new Tuple<string, string>((string)template.SelectedItem, text.Text);
        }
        return null;
    }

    public async void Toast()
    {
        Tuple<string, string> result = await Dialog();
        if (result != null)
        {
            UpdateToast(result.Item1, result.Item2);
        }
    }
}

Step 8

Then in the Solution Explorer select MainPage.xaml

vs2017-library-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:

<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Name="Toast" Icon="Comment" Label="Toast" Click="Toast_Click"/>
</CommandBar>

It should appear as such:

xaml-toast-styles

Step 11

From the Menu choose View and then Code

vs2017-view-code

Step 12

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

Library library = new Library();

private void Toast_Click(object sender, RoutedEventArgs e)
{
	library.Toast();
}

It should then appear as such:

code-toast-styles

Step 13

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

vs2017-debug

Step 14

Once started the Application should then appear

run-toast-styles

Step 15

After the Application has started running you can then select Toast display a Dialog where you select Style from the ComboBox and Text. The Toast will be displayed in Windows 10 in the Action Centre with the Text entered.

ran-toast-styles

Step 16

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Universal Windows Platform – Tile Styles

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 locate and select Visual Studio 2017.

vs2017-home

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

Step 4

Then in New Universal Windows Project you need to select the Target Version to be Windows 10 Creators Update (10.0; Build 15063) and the Minimum Version to be at least Windows 10 Anniversary Update (10.0; Build 14393) or Windows 10 Creators Update (10.0; Build 15063)

vs2017-platform

Step 5

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 6

From the Add New Item choose Visual C# from Installed then choose Code then select Code File and then in the Name as Library.cs and then select Add to add the file to the Project

vs2017-library

Step 7

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Core;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using Windows.UI.StartScreen;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

public class Library
{
    public IEnumerable<string> GetTemplates()
    {
        return Enum.GetValues(typeof(TileTemplateType)).Cast<TileTemplateType>()
            .Select(s => s.ToString()).Distinct();
    }

    private void UpdateTile(string style, string value)
    {
        TileTemplateType template = (TileTemplateType)Enum.Parse(typeof(TileTemplateType), style);
        XmlDocument tile = TileUpdateManager.GetTemplateContent(template);
        XmlNodeList text = tile.GetElementsByTagName("text");
        if (text.Length > 0)
        {
            for (int i = 0; i < text.Length; i++)
            {
                text[i].AppendChild(tile.CreateTextNode(value));
            }
        }
        XmlNodeList image = tile.GetElementsByTagName("image");
        if (image.Length > 0)
        {
            for (int i = 0; i < image.Length; i++)
            {
                image[i].Attributes.GetNamedItem("src").NodeValue =
                "Assets/Square44x44Logo.scale-200.png";
            }
        }
        TileNotification notification = new TileNotification(tile);
        string output = tile.GetXml(); 
        TileUpdateManager.CreateTileUpdaterForApplication().Update(notification);
    }

    private async Task<Tuple<string, string>> Dialog()
    {
        ComboBox template = new ComboBox()
        {
            HorizontalAlignment = HorizontalAlignment.Stretch,
            Margin = new Thickness(5),
            ItemsSource = GetTemplates()
        };
        template.SelectedIndex = 0;
        TextBox text = new TextBox()
        {
            PlaceholderText = "Text",
            Margin = new Thickness(5)
        };
        StackPanel panel = new StackPanel()
        {
            Orientation = Orientation.Vertical
        };
        panel.Children.Add(template);
        panel.Children.Add(text);
        ContentDialog dialog = new ContentDialog()
        {
            Title = "Tile Styles",
            PrimaryButtonText = "Update",
            CloseButtonText = "Cancel",
            Content = panel
        };
        ContentDialogResult result = await dialog.ShowAsync();
        if (result == ContentDialogResult.Primary)
        {
            return new Tuple<string, string>((string)template.SelectedItem, text.Text);
        }
        return null;
    }

    public async Task<bool> PinAsync()
    {
        bool isPinned = false;
        AppListEntry entry = (await Package.Current.GetAppListEntriesAsync()).FirstOrDefault();
        if (entry != null)
        {
            isPinned = await StartScreenManager.GetDefault().ContainsAppListEntryAsync(entry);
        }
        if (!isPinned)
        {
            isPinned = await StartScreenManager.GetDefault().RequestAddAppListEntryAsync(entry);
        }
        return isPinned;
    }

    public async void Tile()
    {
        Tuple<string, string> result = await Dialog();
        if (result != null)
        {
            UpdateTile(result.Item1, result.Item2);
        }
    }
}

Step 8

Then in the Solution Explorer select MainPage.xaml

vs2017-library-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:

<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Name="Pin" Icon="Pin" Label="Pin" Click="Pin_Click"/>
	<AppBarButton Name="Tile" Icon="SetTile" Label="Tile" Click="Tile_Click"/>
</CommandBar>

It should appear as such:

xaml-tile-style

Step 11

From the Menu choose View and then Code

vs2017-view-code

Step 12

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

Library library = new Library();

private async void Pin_Click(object sender, RoutedEventArgs e)
{
	await library.PinAsync();
}

private void Tile_Click(object sender, RoutedEventArgs e)
{
	library.Tile();
}

It should then appear as such:

code-tile-style

Step 13

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

vs2017-debug

Step 14

Once started the Application should then appear

run-tile-style

Step 15

After the Application has started running you can then select Pin to pin-to-start the Application and then select Tile display a Dialog where you select Style from the ComboBox and Text. The Tile will be displayed in Windows 10 on the Start Menu for the Application using the Template with the Text entered.

ran-tile-style

Step 16

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Universal Windows Platform – Badges

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 locate and select Visual Studio 2017.

vs2017-home

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

Step 4

Then in New Universal Windows Project you need to select the Target Version to be Windows 10 Creators Update (10.0; Build 15063) and the Minimum Version to be at least Windows 10 Anniversary Update (10.0; Build 14393) or Windows 10 Creators Update (10.0; Build 15063)

vs2017-platform

Step 5

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 6

From the Add New Item choose Visual C# from Installed then choose Code then select Code File and then in the Name as Library.cs and then select Add to add the file to the Project

vs2017-library

Step 7

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Core;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using Windows.UI.StartScreen;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

public class Library
{
    private List<string> glyphs = new List<string>
    {
        "number", "activity", "alarm", "attention", "available", "away",
        "busy", "error", "newMessage", "paused", "playing", "unavailable"
    };

    private async Task<string> Dialog()
    {
        ComboBox glyph = new ComboBox()
        {
            HorizontalAlignment = HorizontalAlignment.Stretch,
            Margin = new Thickness(5),
            ItemsSource = glyphs
        };
        glyph.SelectedIndex = 0;
        TextBox number = new TextBox()
        {
            PlaceholderText = "Number",
            Margin = new Thickness(5)
        };
        StackPanel panel = new StackPanel()
        {
            Orientation = Orientation.Vertical
        };
        panel.Children.Add(glyph);
        panel.Children.Add(number);
        ContentDialog dialog = new ContentDialog()
        {
            Title = "Badges",
            PrimaryButtonText = "Update",
            CloseButtonText = "Cancel",
            Content = panel
        };
        ContentDialogResult result = await dialog.ShowAsync();
        if (result == ContentDialogResult.Primary)
        {
            string selected = (string)glyph.SelectedItem;
            return (selected == "number") ? number.Text : selected;
        }
        return null;
    }

    private void UpdateBadge(string value)
    {
        bool isNumber = int.TryParse(value, out int number);
        XmlDocument badge = BadgeUpdateManager.GetTemplateContent(isNumber ?
            BadgeTemplateType.BadgeNumber : BadgeTemplateType.BadgeGlyph);
        XmlNodeList attributes = badge.GetElementsByTagName("badge");
        IXmlNode node = attributes[0].Attributes.GetNamedItem("value");
        node.NodeValue = value;
        BadgeNotification notification = new BadgeNotification(badge);
        BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(notification);
    }

    public async Task<bool> PinAsync()
    {
        bool isPinned = false;
        AppListEntry entry = (await Package.Current.GetAppListEntriesAsync()).FirstOrDefault();
        if (entry != null)
        {
            isPinned = await StartScreenManager.GetDefault().ContainsAppListEntryAsync(entry);
        }
        if (!isPinned)
        {
            isPinned = await StartScreenManager.GetDefault().RequestAddAppListEntryAsync(entry);
        }
        return isPinned;
    }

    public async void Badge()
    {
        string result = await Dialog();
        if(result != null)
        {
            UpdateBadge(result);
        }
    }
}

Step 8

Then in the Solution Explorer select MainPage.xaml

vs2017-library-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:

<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Name="Pin" Icon="Pin" Label="Pin" Click="Pin_Click"/>
	<AppBarButton Name="Badge" Icon="SetTile" Label="Badge" Click="Badge_Click"/>
</CommandBar>

It should appear as such:

xaml-badges

Step 11

From the Menu choose View and then Code

vs2017-view-code

Step 12

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

Library library = new Library();

private async void Pin_Click(object sender, RoutedEventArgs e)
{
	await library.PinAsync();
}

private void Badge_Click(object sender, RoutedEventArgs e)
{
	library.Badge();
}

It should then appear as such:

code-badges

Step 13

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

vs2017-debug

Step 14

Once started the Application should then appear

run-badges

Step 15

After the Application has started running you can then select Pin to pin-to-start the Application and then select Badge display a Dialog where you select Number or Glyph from the ComboBox and Number to use if that option has been selected from the ComboBox. The Badge will be displayed in Windows 10 on the TaskBar or the Tile for the Application.

ran-badges

Step 16

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Universal Windows Platform – Docking Control

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 locate and select Visual Studio 2017.

vs2017-home

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 the Name as DockingControl, then select a Location and then select Ok to create the Project

vs2017-new-project

Step 4

Then in New Universal Windows Project you need to select the Target Version to be Windows 10 Creators Update (10.0; Build 15063) and the Minimum Version to be at least Windows 10 Anniversary Update (10.0; Build 14393) or Windows 10 Creators Update (10.0; Build 15063)

vs2017-platform

Step 5

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 6

From the Add New Item choose Visual C# from Installed then choose Code then select Code File and then set the Name as Docking.cs and then select Add to add the file to the Project

class-docking-control

Step 7

Then in the Code View for Docking.cs the following should be entered:

using System;
using System.Globalization;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

namespace DockingControl
{
    public class Docking : Panel
    {
        private static bool _ignorePropertyChange;

        public enum Dock
        {
            Left = 0,
            Top = 1,
            Right = 2,
            Bottom = 3
        }

        private static void OnLastChildFillPropertyChanged(DependencyObject d, 
            DependencyPropertyChangedEventArgs e)
        {
            if (d is Docking panel)
                panel.InvalidateArrange();
        }

        private static void OnDockPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (_ignorePropertyChange)
            {
                _ignorePropertyChange = false;
                return;
            }
            UIElement element = (UIElement)d;
            Dock value = (Dock)e.NewValue;
            if ((value != Dock.Left) && (value != Dock.Top) &&
                (value != Dock.Right) && (value != Dock.Bottom))
            {
                _ignorePropertyChange = true;
                element.SetValue(DockProperty, (Dock)e.OldValue);
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "InvalidValue", value), "value");
            }
            if (VisualTreeHelper.GetParent(element) is Docking panel)
                panel.InvalidateMeasure();
        }

        public static readonly DependencyProperty LastChildFillProperty =
        DependencyProperty.Register("LastChildFill", typeof(bool),
        typeof(Docking), new PropertyMetadata(true, OnLastChildFillPropertyChanged));

        public static readonly DependencyProperty DockProperty = 
        DependencyProperty.RegisterAttached("Dock", typeof(Dock),
        typeof(Docking), new PropertyMetadata(Dock.Left, OnDockPropertyChanged));

        public bool LastChildFill
        {
            get { return (bool)GetValue(LastChildFillProperty); }
            set { SetValue(LastChildFillProperty, value); }
        }

        public static Dock GetDock(UIElement element)
        {
            if (element == null) throw new ArgumentNullException("element");
            return (Dock)element.GetValue(DockProperty);
        }

        public static void SetDock(UIElement element, Dock dock)
        {
            if (element == null) throw new ArgumentNullException("element");
            element.SetValue(DockProperty, dock);
        }

        protected override Size ArrangeOverride(Size size)
        {
            double left = 0.0;
            double top = 0.0;
            double right = 0.0;
            double bottom = 0.0;
            UIElementCollection children = Children;
            int count = children.Count - (LastChildFill ? 1 : 0);
            int index = 0;
            foreach (UIElement element in children)
            {
                Rect rect = new Rect(left, top,
                  Math.Max(0.0, size.Width - left - right),
                  Math.Max(0.0, size.Height - top - bottom));
                if (index < count)
                {
                    Size desiredSize = element.DesiredSize;
                    switch (GetDock(element))
                    {
                        case Dock.Left:
                            left += desiredSize.Width;
                            rect.Width = desiredSize.Width;
                            break;
                        case Dock.Top:
                            top += desiredSize.Height;
                            rect.Height = desiredSize.Height;
                            break;
                        case Dock.Right:
                            right += desiredSize.Width;
                            rect.X = Math.Max(0.0, size.Width - right);
                            rect.Width = desiredSize.Width;
                            break;
                        case Dock.Bottom:
                            bottom += desiredSize.Height;
                            rect.Y = Math.Max(0.0, size.Height - bottom);
                            rect.Height = desiredSize.Height;
                            break;
                    }
                }
                element.Arrange(rect);
                index++;
            }
            return size;
        }

        protected override Size MeasureOverride(Size size)
        {
            double width = 0.0;
            double height = 0.0;
            double maxWidth = 0.0;
            double maxHeight = 0.0;
            foreach (UIElement element in Children)
            {
                Size remainingSize = new Size(
                    Math.Max(0.0, size.Width - width),
                    Math.Max(0.0, size.Height - height));
                element.Measure(remainingSize);
                Size desired = element.DesiredSize;
                switch (GetDock(element))
                {
                    case Dock.Left:
                    case Dock.Right:
                        maxHeight = Math.Max(maxHeight, height + desired.Height);
                        width += desired.Width;
                        break;
                    case Dock.Top:
                    case Dock.Bottom:
                        maxWidth = Math.Max(maxWidth, width + desired.Width);
                        height += desired.Height;
                        break;
                }
            }
            maxWidth = Math.Max(maxWidth, width);
            maxHeight = Math.Max(maxHeight, height);
            return new Size(maxWidth, maxHeight);
        }
    }
}

Step 8

From the Menu choose Build and then Build Solution

vs2017-build

Step 9

Then in the Solution Explorer select MainPage.xaml

vs2017-library-mainpage

Step 10

From the Menu choose View and then Designer

vs2017-view-designer

Step 11

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

<local:Docking HorizontalAlignment="Center" VerticalAlignment="Center">
	<Rectangle Width="100" Height="100" Fill="Red" Margin="10" local:Docking.Dock="Top"/>
	<Rectangle Width="100" Height="100" Fill="Orange" Margin="10" local:Docking.Dock="Bottom"/>
	<Rectangle Width="100" Height="100" Fill="Yellow" Margin="10" local:Docking.Dock="Left"/>
	<Rectangle Width="100" Height="100" Fill="Green" Margin="10" local:Docking.Dock="Right"/>
	<Rectangle Width="100" Height="100" Fill="Cyan" Margin="10"/>
</local:Docking>

It should appear as such:

xaml-docking-control

Step 12

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

vs2017-debug

Step 13

Once started the Application should then appear displaying the Docking Control with items docked to the Top, Bottom, Left and Right

run-docking-control

Step 14

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Universal Windows Platform – Uniform Control

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 locate and select Visual Studio 2017.

vs2017-home

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 the Name as UniformControl, then select a Location and then select Ok to create the Project

vs2017-new-project

Step 4

Then in New Universal Windows Project you need to select the Target Version to be Windows 10 Creators Update (10.0; Build 15063) and the Minimum Version to be at least Windows 10 Anniversary Update (10.0; Build 14393) or Windows 10 Creators Update (10.0; Build 15063)

vs2017-platform

Step 5

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 6

From the Add New Item choose Visual C# from Installed then choose Code then select Code File and then set the Name as Uniform.cs and then select Add to add the file to the Project

class-uniform-control

Step 7

Then in the Code View for Uniform.cs the following should be entered:

using System;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace UniformControl
{
    public class Uniform : Panel
    {
        private int _columns;
        private int _rows;

        public static readonly DependencyProperty ColumnsProperty =
            DependencyProperty.Register("Columns", typeof(int),
            typeof(Uniform), new PropertyMetadata(0));

        public static readonly DependencyProperty FirstColumnProperty =
        DependencyProperty.Register("FirstColumn", typeof(int),
            typeof(Uniform), new PropertyMetadata(0));

        public static readonly DependencyProperty RowsProperty =
            DependencyProperty.Register("Rows", typeof(int),
                typeof(Uniform), new PropertyMetadata(0));

        public int Columns
        {
            get { return (int)GetValue(ColumnsProperty); }
            set { SetValue(ColumnsProperty, value); }
        }

        public int FirstColumn
        {
            get { return (int)GetValue(FirstColumnProperty); }
            set { SetValue(FirstColumnProperty, value); }
        }

        public int Rows
        {
            get { return (int)GetValue(RowsProperty); }
            set { SetValue(RowsProperty, value); }
        }

        private void UpdateComputedValues()
        {
            _columns = Columns;
            _rows = Rows;
            if (FirstColumn >= _columns) FirstColumn = 0;
            if ((_rows == 0) || (_columns == 0))
            {
                var row = 0;
                var column = 0;
                int count = Children.Count;
                while (column < count)
                {
                    UIElement element = Children[column];
                    if (element.Visibility != Visibility.Collapsed)
                    {
                        row++;
                    }
                    column++;
                }
                if (row == 0) row = 1;
                if (_rows == 0)
                {
                    if (_columns > 0)
                    {
                        _rows = ((row + FirstColumn) + (_columns - 1)) / _columns;
                    }
                    else
                    {
                        _rows = (int)Math.Sqrt(row);
                        if ((_rows * _rows) < row)
                        {
                            _rows++;
                        }
                        _columns = _rows;
                    }
                }
                else if (_columns == 0)
                {
                    _columns = (row + (_rows - 1)) / _rows;
                }
            }
        }

        protected override Size ArrangeOverride(Size size)
        {
            Rect rectangle = new Rect(0.0, 0.0,
                size.Width / _columns, size.Height / _rows);
            double width = rectangle.Width;
            double value = size.Width - 1.0;
            rectangle.X += rectangle.Width * FirstColumn;
            foreach (UIElement element in Children)
            {
                element.Arrange(rectangle);
                if (element.Visibility != Visibility.Collapsed)
                {
                    rectangle.X += width;
                    if (rectangle.X >= value)
                    {
                        rectangle.Y += rectangle.Height;
                        rectangle.X = 0.0;
                    }
                }
            }
            return size;
        }

        protected override Size MeasureOverride(Size size)
        {
            UpdateComputedValues();
            Size available = new Size(size.Width / (_columns), size.Height / (_rows));
            double width = 0.0;
            double height = 0.0;
            int value = 0;
            int count = Children.Count;
            while (value < count)
            {
                UIElement element = Children[value];
                element.Measure(available);
                Size desired = element.DesiredSize;
                if (width < desired.Width) width = desired.Width;
                if (height < desired.Height) height = desired.Height;
                value++;
            }
            return new Size(width * _columns, height * _rows);
        }
    }
}

Step 8

From the Menu choose Build and then Build Solution

vs2017-build

Step 9

Then in the Solution Explorer select MainPage.xaml

vs2017-library-mainpage

Step 10

From the Menu choose View and then Designer

vs2017-view-designer

Step 11

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

<local:Uniform HorizontalAlignment="Center" VerticalAlignment="Center">
	<Rectangle Width="75" Height="75" Fill="Black" Margin="5"/>
	<Rectangle Width="75" Height="75" Fill="Red"/>
	<Rectangle Width="75" Height="75" Fill="Orange"/>
	<Rectangle Width="75" Height="75" Fill="Yellow"/>
	<Rectangle Width="75" Height="75" Fill="Green"/>
	<Rectangle Width="75" Height="75" Fill="Cyan"/>
	<Rectangle Width="75" Height="75" Fill="Blue"/>
	<Rectangle Width="75" Height="75" Fill="Magenta"/>
	<Rectangle Width="75" Height="75" Fill="Purple"/>
</local:Uniform>

It should appear as such:

xaml-uniform-control

Step 12

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

vs2017-debug

Step 13

Once started the Application should then appear displaying the Uniform Control with some items where the size of each element is determined by the first item in the control

run-uniform-control

Step 14

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Universal Windows Platform – Directs Control

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 locate and select Visual Studio 2017.

vs2017-home

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

Step 4

Then in New Universal Windows Project you need to select the Target Version to be Windows 10 Creators Update (10.0; Build 15063) and the Minimum Version to be at least Windows 10 Anniversary Update (10.0; Build 14393) or Windows 10 Creators Update (10.0; Build 15063)

vs2017-platform

Step 5

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 6

From the Add New Item choose Visual C# from Installed then choose XAML then select User Control and then in the Name as Directs.xaml and then select Add to add the file to the Project

user-directs-control

Step 7

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

<Viewbox>
	<Grid Name="Pad" Width="180" Height="180" Loaded="Pad_Loaded">
		<Grid.ColumnDefinitions>
			<ColumnDefinition Width="*"/>
			<ColumnDefinition Width="Auto"/>
			<ColumnDefinition Width="*"/>
		</Grid.ColumnDefinitions>
		<Grid.RowDefinitions>
			<RowDefinition Height="*"/>
			<RowDefinition Height="Auto"/>
			<RowDefinition Height="*"/>
		</Grid.RowDefinitions>
		<Path Name="Up" Grid.Row="0" Grid.Column="1" Grid.RowSpan="2" VerticalAlignment="Top" Margin="5"
		  Data="M 0,0 40,0 40,60 20,80 0,60 0,0 z" Fill="{Binding Foreground}" PointerMoved="Pad_PointerMoved"/>
		<Path Name="Down" Grid.Row="1" Grid.Column="1" Grid.RowSpan="2" VerticalAlignment="Bottom" Margin="5"
		  Data="M 0,20 20,0 40,20 40,80 0,80 z" Fill="{Binding Foreground}" PointerMoved="Pad_PointerMoved"/>
		<Path Name="Left" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Left" Margin="5"
		  Data="M 0,0 60,0 80,20 60,40 0,40 z" Fill="{Binding Foreground}" PointerMoved="Pad_PointerMoved"/>
		<Path Name="Right" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" HorizontalAlignment="Right" Margin="5"
		  Data="M 0,20 20,0 80,0 80,40 20,40 z" Fill="{Binding Foreground}" PointerMoved="Pad_PointerMoved"/>
	</Grid>
</Viewbox>

It should appear as such:

xaml-user-directs-control

Step 8

From the Menu choose View and then Code

vs2017-view-code

Step 9

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

public enum Directions
{
	Up = 0,
	Down = 1,
	Left = 2,
	Right = 3
}

public delegate void DirectionEvent(object sender, Directions direction);
public event DirectionEvent Direction;

private void Pad_Loaded(object sender, RoutedEventArgs e)
{
	this.DataContext = this;
}

private void Pad_PointerMoved(object sender, PointerRoutedEventArgs e)
{
	Windows.UI.Input.PointerPoint point = e.GetCurrentPoint(Pad);
	bool fire = (e.Pointer.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Mouse) ?
		point.Properties.IsLeftButtonPressed : point.IsInContact;
	if (fire)
	{
		Windows.UI.Xaml.Shapes.Path path = ((Windows.UI.Xaml.Shapes.Path)sender);
		if (Direction != null)
		{
			this.Direction(path, (Directions)Enum.Parse(typeof(Directions), path.Name));
		}
	}
}

Step 10

From the Menu choose Build and then Build Solution

vs2017-build

Step 11

Then in the Solution Explorer select MainPage.xaml

vs2017-library-mainpage

Step 12

From the Menu choose View and then Designer

vs2017-view-designer

Step 13

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

<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
	<TextBlock Name="Label" HorizontalAlignment="Center" Style="{StaticResource SubtitleTextBlockStyle}"/>
	<local:Directs x:Name="Pad" Height="300" Width="300" Foreground="{ThemeResource AccentButtonBackground}" 
		Direction="Pad_Direction"/>
</StackPanel>

It should appear as such:

xaml-directs-control

Step 14

From the Menu choose View and then Code

vs2017-view-code

Step 15

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

private void Pad_Direction(object sender, Directs.Directions direction)
{
	Label.Text = direction.ToString();
}

It should then appear as such:

code-directs-control

Step 16

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

vs2017-debug

Step 17

Once started the Application should then appear

run-directs-control

Step 18

After the Application has started running you can then select the parts of the Directs Control for Up, Down, Left and Right.

ran-directs-control

Step 19

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Universal Windows Platform – Stacked Control

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 locate and select Visual Studio 2017.

vs2017-home

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

Step 4

Then in New Universal Windows Project you need to select the Target Version to be Windows 10 Creators Update (10.0; Build 15063) and the Minimum Version to be at least Windows 10 Anniversary Update (10.0; Build 14393) or Windows 10 Creators Update (10.0; Build 15063)

vs2017-platform

Step 5

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 6

From the Add New Item choose Visual C# from Installed then choose XAML then select User Control and then in the Name as Stacked.xaml and then select Add to add the file to the Project

user-stacked-control

Step 7

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

<Viewbox>
	<Grid Name="Display" Width="100"/>
</Viewbox>

It should appear as such:

xaml-user-stacked-control

Step 8

From the Menu choose View and then Code

vs2017-view-code

Step 9

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

private List<Windows.UI.Color> _palette = new List<Windows.UI.Color>();
private List<double> _items = new List<double>();

private List<double> Percentages()
{
	List<double> results = new List<double>();
	double total = _items.Sum();
	foreach(double item in _items)
	{
		results.Add((item / total) * 100);
	}
	return results.OrderBy(o => o).ToList();
}

private Windows.UI.Xaml.Shapes.Rectangle GetRectangle(Windows.UI.Color colour, int column)
{
	Windows.UI.Xaml.Shapes.Rectangle rectangle = new Windows.UI.Xaml.Shapes.Rectangle()
	{
		Height = 10,
		Stretch = Stretch.UniformToFill,
		Fill = new SolidColorBrush(colour)
	};
	rectangle.SetValue(Grid.ColumnProperty, column);
	return rectangle;
}

private void Layout()
{
	List<double> percentages = Percentages();           
	Display.ColumnDefinitions.Clear();
	for (int index = 0; index < percentages.Count(); index++)
	{
		double percentage = percentages[index];
		ColumnDefinition column = new ColumnDefinition()
		{
			Width = new GridLength(percentage, GridUnitType.Star)
		};
		Display.ColumnDefinitions.Add(column);
		Windows.UI.Color colour = (index < _palette.Count()) 
			? _palette[index] : Windows.UI.Colors.Black;
		Display.Children.Add(GetRectangle(colour, index));
	}
}

public List<Windows.UI.Color> Palette
{
	get { return _palette; }
	set { _palette = value; }
}

public List<double> Items
{
	get { return _items; }
	set { _items = value; Layout(); }
}

Step 10

From the Menu choose Build and then Build Solution

vs2017-build

Step 11

Then in the Solution Explorer select MainPage.xaml

vs2017-library-mainpage

Step 12

From the Menu choose View and then Designer

vs2017-view-designer

Step 13

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

<local:Stacked x:Name="Display" Margin="50" Loaded="Display_Loaded"/>

It should appear as such:

xaml-stacked-control

Step 14

From the Menu choose View and then Code

vs2017-view-code

Step 15

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

private void Display_Loaded(object sender, RoutedEventArgs e)
{
	Display.Palette = new List<Windows.UI.Color>()
	{
		Windows.UI.Colors.Black,
		Windows.UI.Colors.Gray,
		Windows.UI.Colors.Red,
		Windows.UI.Colors.Orange,
		Windows.UI.Colors.Yellow,
		Windows.UI.Colors.Green,
		Windows.UI.Colors.Cyan,
		Windows.UI.Colors.Blue,
		Windows.UI.Colors.Magenta,
		Windows.UI.Colors.Purple,
	};
	Func<int, int> fibonacci = null;
	fibonacci = value => value > 1 ? 
		fibonacci(value - 1) + fibonacci(value - 2) : value;
	Display.Items = Enumerable.Range(0, Display.Palette.Count())
		.Select(fibonacci).Select(s => (double)s).ToList();
}

It should then appear as such:

code-stacked-control

Step 16

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

vs2017-debug

Step 17

Once started the Application should then appear displaying a Stacked CHart based on the Palette and the Items set

run-stacked-control

Step 18

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Universal Windows Platform – Lights Control

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 locate and select Visual Studio 2017.

vs2017-home

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

Step 4

Then in New Universal Windows Project you need to select the Target Version to be Windows 10 Creators Update (10.0; Build 15063) and the Minimum Version to be at least Windows 10 Anniversary Update (10.0; Build 14393) or Windows 10 Creators Update (10.0; Build 15063)

vs2017-platform

Step 5

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 6

From the Add New Item choose Visual C# from Installed then choose XAML then select User Control and then in the Name as Lights.xaml and then select Add to add the file to the Project

user-lights-control

Step 7

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

<Viewbox>
	<ItemsControl Name="Display" Loaded="Display_Loaded">
		<ItemsControl.ItemTemplate>
			<DataTemplate>
				<Grid>
					<Ellipse Height="100" Width="100" Margin="5">
						<Ellipse.Fill>
							<SolidColorBrush Color="{Binding Colour}"/>
						</Ellipse.Fill>
					</Ellipse>
					<Ellipse Height="100" Width="100" Margin="5" Visibility="{Binding Off}">
						<Ellipse.Fill>
							<SolidColorBrush Color="Black"/>
						</Ellipse.Fill>
					</Ellipse>
				</Grid>
			</DataTemplate>
		</ItemsControl.ItemTemplate>
		<ItemsControl.ItemsPanel>
			<ItemsPanelTemplate>
				<StackPanel Orientation="{Binding Path=Orientation}"/>
			</ItemsPanelTemplate>
		</ItemsControl.ItemsPanel>
	</ItemsControl>
</Viewbox>

It should appear as such:

xaml-user-lights-control

Step 8

From the Menu choose View and then Code

vs2017-view-code

Step 9

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

public class Item : System.ComponentModel.INotifyPropertyChanged
{
	private bool _isOn;
	private Windows.UI.Color _colour;

	public virtual void OnPropertyChanged(string propertyName)
	{
		PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
	}
	public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

	public bool IsOn
	{
		get { return _isOn; }
		set
		{
			_isOn = value;
			OnPropertyChanged("IsOn");
			OnPropertyChanged("Off");
		}
	}

	public Visibility Off
	{
		get { return IsOn ? Visibility.Collapsed : Visibility.Visible; }
	}

	public Windows.UI.Color Colour
	{
		get { return _colour; }
		set { _colour = value; OnPropertyChanged("Colour"); }
	}
}

private System.Collections.ObjectModel.ObservableCollection<Item> _items =
		new System.Collections.ObjectModel.ObservableCollection<Item>();

private Orientation _orientation = Orientation.Vertical;

public System.Collections.ObjectModel.ObservableCollection<Item> Items
{
	get { return _items; }
	set { _items = value; Display.ItemsSource = Items; }
}

public Orientation Orientation {
	get { return _orientation; }
	set { _orientation = value; }
}

private void Display_Loaded(object sender, RoutedEventArgs e)
{
	this.DataContext = this;
}

Step 10

From the Menu choose Build and then Build Solution

vs2017-build

Step 11

Then in the Solution Explorer select MainPage.xaml

vs2017-library-mainpage

Step 12

From the Menu choose View and then Designer

vs2017-view-designer

Step 13

The Design View will be displayed along with the XAML View and in this below &;lt;Grid> enter the following XAML:

<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Name="Play" Icon="Play" Label="Play" Click="Play_Click"/>
</CommandBar>
<local:Lights x:Name="Display" Height="300" Width="300" Orientation="Vertical" Loaded="Display_Loaded"/>

It should appear as such:

xaml-lights-control

Step 14

From the Menu choose View and then Code

vs2017-view-code

Step 15

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

private const int red = 0;
private const int orange = 1;
private const int green = 2;

private async System.Threading.Tasks.Task<bool> Delay(int seconds = 2)
{
	await System.Threading.Tasks.Task.Delay(seconds * 1000);
	return true;
}

private void Display_Loaded(object sender, RoutedEventArgs e)
{
	Display.Items = new System.Collections.ObjectModel.ObservableCollection<Lights.Item>() {
		new Lights.Item() { Colour = Windows.UI.Colors.Red },
		new Lights.Item() { Colour = Windows.UI.Colors.Orange },
		new Lights.Item() { Colour = Windows.UI.Colors.Green, IsOn = true }
	};
}

private async void Play_Click(object sender, RoutedEventArgs e)
{
	Display.Items[red].IsOn = false;
	Display.Items[orange].IsOn = false;
	Display.Items[green].IsOn = true;
	await Delay();
	Display.Items[green].IsOn = false;  
	await Delay();
	Display.Items[orange].IsOn = true;
	await Delay();
	Display.Items[orange].IsOn = false;
	await Delay();
	Display.Items[red].IsOn = true;
	await Delay();
	Display.Items[red].IsOn = true;
	await Delay();
	Display.Items[orange].IsOn = true;
	await Delay();
	Display.Items[red].IsOn = false;
	Display.Items[orange].IsOn = false;
	Display.Items[green].IsOn = true;
	await Delay();
}

It should then appear as such:

code-lights-control

Step 16

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

vs2017-debug

Step 17

Once started the Application should then appear

run-lights-control

Step 18

After the Application has started running you can then select Play to go cycle through the UK traffic light sequence displayed using the Lights Control.

ran-lights-control

Step 19

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License