Universal Windows Platform – Docking Control

Step 1

Enable your device for Developer Mode, if not done already then in Windows 10, choose Start and then Settings

win10-settings

From Windows Settings choose Update & security

win10-update

Then choose For developers and select Developer mode

win10-dev

Step 2

In Windows 10 you need to choose Start then Visual Studio 2017

vs2017-home

If this is not already Downloaded and Installed then Download Visual Studio Community 2017 and then select Run

vs2017-download

Once Visual Studio Community 2017 has been downloaded then you will need to Run the Visual Studio Installer

vs2017-install.png

Then select Continue to prepare the installation, once ready you then to select at least the Universal Windows Platform development option from Workloads in the Visual Studio Installer and then choose Install and follow any on-screen instructions

vs2017-workload

Step 3

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

vs2017-file-new-project

Step 4

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 5

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 6

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 7

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 8

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 9

From the Menu choose Build and then Build Solution

vs2017-build

Step 10

Then in the Solution Explorer select MainPage.xaml

vs2017-library-mainpage

Step 11

From the Menu choose View and then Designer

vs2017-view-designer

Step 12

The Design View will be displayed along withA the XAML View and in this below 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 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 displaying the Docking Control with items docked to the Top, Bottom, Left and Right

run-docking-control

Step 15

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Universal Windows Platform – Uniform Control

Step 1

Enable your device for Developer Mode, if not done already then in Windows 10, choose Start and then Settings

win10-settings

From Windows Settings choose Update & security

win10-update

Then choose For developers and select Developer mode

win10-dev

Step 2

In Windows 10 you need to choose Start then Visual Studio 2017

vs2017-home

If this is not already Downloaded and Installed then Download Visual Studio Community 2017 and then select Run

vs2017-download

Once Visual Studio Community 2017 has been downloaded then you will need to Run the Visual Studio Installer

vs2017-install.png

Then select Continue to prepare the installation, once ready you then to select at least the Universal Windows Platform development option from Workloads in the Visual Studio Installer and then choose Install and follow any on-screen instructions

vs2017-workload

Step 3

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

vs2017-file-new-project

Step 4

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 5

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 6

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 7

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 8

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 9

From the Menu choose Build and then Build Solution

vs2017-build

Step 10

Then in the Solution Explorer select MainPage.xaml

vs2017-library-mainpage

Step 11

From the Menu choose View and then Designer

vs2017-view-designer

Step 12

The Design View will be displayed along withA the XAML View and in this below 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 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 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 15

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Universal Windows Platform – Directs Control

Step 1

Enable your device for Developer Mode, if not done already then in Windows 10, choose Start and then Settings

win10-settings

From Windows Setttings choose Update & security

win10-update

Then choose For developers and select Developer mode

win10-dev

Step 2

In Windows 10 you need to choose Start then Visual Studio 2017

vs2017-home

If this is not already Downloaded and Installed then Download Visual Studio Community 2017 and then select Run

vs2017-download

Once Visual Studio Community 2017 has been downloaded then you will need to Run the Visual Studio Installer

vs2017-install.png

Then select Continue to prepare the installation, once ready you then to select at least the Universal Windows Platform development option from Workloads in the Visual Studio Installer and then choose Install and follow any on-screen instructions

vs2017-workload

Step 3

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

vs2017-file-new-project

Step 4

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 5

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 6

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 7

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 8

The Design View will be displayed along with the XAML View and in this below 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 9

From the Menu choose View and then Code

vs2017-view-code

Step 10

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 11

From the Menu choose Build and then Build Solution

vs2017-build

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 below &;lt;Grid> 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 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:

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

It should then appear as such:

code-directs-control

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-directs-control

Step 19

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 20

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Universal Windows Platform – Stacked Control

Step 1

Enable your device for Developer Mode, if not done already then in Windows 10, choose Start and then Settings

win10-settings

From Windows Setttings choose Update & security

win10-update

Then choose For developers and select Developer mode

win10-dev

Step 2

In Windows 10 you need to choose Start then Visual Studio 2017

vs2017-home

If this is not already Downloaded and Installed then Download Visual Studio Community 2017 and then select Run

vs2017-download

Once Visual Studio Community 2017 has been downloaded then you will need to Run the Visual Studio Installer

vs2017-install.png

Then select Continue to prepare the installation, once ready you then to select at least the Universal Windows Platform development option from Workloads in the Visual Studio Installer and then choose Install and follow any on-screen instructions

vs2017-workload

Step 3

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

vs2017-file-new-project

Step 4

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 5

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 6

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 7

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 8

The Design View will be displayed along with the XAML View and in this below enter the following XAML:

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

It should appear as such:

xaml-user-stacked-control

Step 9

From the Menu choose View and then Code

vs2017-view-code

Step 10

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 11

From the Menu choose Build and then Build Solution

vs2017-build

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 below enter the following XAML:

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

It should appear as such:

xaml-stacked-control

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:

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 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 displaying a Stacked CHart based on the Palette and the Items set

run-stacked-control

Step 19

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Universal Windows Platform – Lights Control

Step 1

Enable your device for Developer Mode, if not done already then in Windows 10, choose Start and then Settings

win10-settings

From Windows Setttings choose Update & security

win10-update

Then choose For developers and select Developer mode

win10-dev

Step 2

In Windows 10 you need to choose Start then Visual Studio 2017

vs2017-home

If this is not already Downloaded and Installed then Download Visual Studio Community 2017 and then select Run

vs2017-download

Once Visual Studio Community 2017 has been downloaded then you will need to Run the Visual Studio Installer

vs2017-install.png

Then select Continue to prepare the installation, once ready you then to select at least the Universal Windows Platform development option from Workloads in the Visual Studio Installer and then choose Install and follow any on-screen instructions

vs2017-workload

Step 3

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

vs2017-file-new-project

Step 4

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 5

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 6

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 7

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 8

The Design View will be displayed along with the XAML View and in this below 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 9

From the Menu choose View and then Code

vs2017-view-code

Step 10

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 11

From the Menu choose Build and then Build Solution

vs2017-build

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

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 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-lights-control

Step 19

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 20

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Universal Windows Platform – Matrix Control

Step 1

Enable your device for Developer Mode, if not done already then in Windows 10, choose Start and then Settings

win10-settings

From Windows Setttings choose Update & security

win10-update

Then choose For developers and select Developer mode

win10-dev

Step 2

In Windows 10 you need to choose Start then Visual Studio 2017

vs2017-home

If this is not already Downloaded and Installed then Download Visual Studio Community 2017 and then select Run

vs2017-download

Once Visual Studio Community 2017 has been downloaded then you will need to Run the Visual Studio Installer

vs2017-install.png

Then select Continue to prepare the installation, once ready you then to select at least the Universal Windows Platform development option from Workloads in the Visual Studio Installer and then choose Install and follow any on-screen instructions

vs2017-workload

Step 3

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

vs2017-file-new-project

Step 4

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 5

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 6

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 7

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

user-matrix-control

Step 8

The Design View will be displayed along with the XAML View and in this below enter the following XAML:

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

It should appear as such:

xaml-user-matrix-control

Step 9

From the Menu choose View and then Code

vs2017-view-code

Step 10

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

private readonly byte[][] table =
{
	new byte[] {
	0,0,0,0,0,0,0,0,
	0,1,1,1,1,1,1,0,
	0,1,1,0,0,1,1,0,
	0,1,1,0,0,1,1,0,
	0,1,1,0,0,1,1,0,
	0,1,1,1,1,1,1,0,
	0,0,0,0,0,0,0,0
	}, // 0
	new byte[] {
	0,0,0,0,0,0,0,0,
	0,0,0,1,1,0,0,0,
	0,1,1,1,1,0,0,0,
	0,0,0,1,1,0,0,0,
	0,0,0,1,1,0,0,0,
	0,0,0,1,1,0,0,0,
	0,0,0,0,0,0,0,0
	}, // 1 
	new byte[] {
	0,0,0,0,0,0,0,0,
	0,1,1,1,1,1,1,0,
	0,0,0,0,0,1,1,0,
	0,1,1,1,1,1,1,0,
	0,1,1,0,0,0,0,0,
	0,1,1,1,1,1,1,0,
	0,0,0,0,0,0,0,0
	}, // 2
	new byte[] {
	0,0,0,0,0,0,0,0,
	0,1,1,1,1,1,1,0,
	0,0,0,0,0,1,1,0,
	0,1,1,1,1,1,1,0,
	0,0,0,0,0,1,1,0,
	0,1,1,1,1,1,1,0,
	0,0,0,0,0,0,0,0
	}, // 3
	new byte[] {
	0,0,0,0,0,0,0,0,
	0,1,1,0,0,1,1,0,
	0,1,1,0,0,1,1,0,
	0,1,1,1,1,1,1,0,
	0,0,0,0,0,1,1,0,
	0,0,0,0,0,1,1,0,
	0,0,0,0,0,0,0,0
	}, // 4
	new byte[] {
	0,0,0,0,0,0,0,0,
	0,1,1,1,1,1,1,0,
	0,1,1,0,0,0,0,0,
	0,1,1,1,1,1,1,0,
	0,0,0,0,0,1,1,0,
	0,1,1,1,1,1,1,0,
	0,0,0,0,0,0,0,0
	}, // 5
	new byte[] {
	0,0,0,0,0,0,0,0,
	0,1,1,1,1,1,1,0,
	0,1,1,0,0,0,0,0,
	0,1,1,1,1,1,1,0,
	0,1,1,0,0,1,1,0,
	0,1,1,1,1,1,1,0,
	0,0,0,0,0,0,0,0
	}, // 6
	new byte[] {
	0,0,0,0,0,0,0,0,
	0,1,1,1,1,1,1,0,
	0,0,0,0,0,1,1,0,
	0,0,0,0,0,1,1,0,
	0,0,0,0,0,1,1,0,
	0,0,0,0,0,1,1,0,
	0,0,0,0,0,0,0,0
	}, // 7
	new byte[] {
	0,0,0,0,0,0,0,0,
	0,1,1,1,1,1,1,0,
	0,1,1,0,0,1,1,0,
	0,1,1,1,1,1,1,0,
	0,1,1,0,0,1,1,0,
	0,1,1,1,1,1,1,0,
	0,0,0,0,0,0,0,0
	}, // 8
	new byte[] {
	0,0,0,0,0,0,0,0,
	0,1,1,1,1,1,1,0,
	0,1,1,0,0,1,1,0,
	0,1,1,1,1,1,1,0,
	0,0,0,0,0,1,1,0,
	0,1,1,1,1,1,1,0,
	0,0,0,0,0,0,0,0
	}, // 9
	new byte[] {
	0,0,0,0,0,0,0,0,
	0,0,0,0,0,0,0,0,
	0,0,0,0,0,0,0,0,
	0,0,0,0,0,0,0,0,
	0,0,0,0,0,0,0,0,
	0,0,0,0,0,0,0,0,
	0,0,0,0,0,0,0,0
	}, // None
	new byte[] {
	0,0,0,0,0,0,0,0,
	0,0,0,1,1,0,0,0,
	0,0,0,1,1,0,0,0,
	0,0,0,0,0,0,0,0,
	0,0,0,1,1,0,0,0,
	0,0,0,1,1,0,0,0,
	0,0,0,0,0,0,0,0
	}, // Colon
	new byte[] {
	0,0,0,0,0,0,0,0,
	0,0,0,0,0,1,1,0,
	0,0,0,0,1,1,0,0,
	0,0,0,1,1,0,0,0,
	0,0,1,1,0,0,0,0,
	0,1,1,0,0,0,0,0,
	0,0,0,0,0,0,0,0
	} // Slash
};
private readonly List<char> symbols =
	new List<char> { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' ', ':', '/' };
private const int columns = 8;
private const int rows = 7;
private const int size = 10;
private byte[,] board = null;
private int count = 0;
private string _output = string.Empty;

private byte[,] AsTwoDimensionalArray(byte[] input, int height, int width)
{
	byte[,] output = new byte[height, width];
	for (int r = 0; r < height; r++)
	{
		for (int c = 0; c < width; c++)
		{
			output[r, c] = input[r * width + c];
		}
	}
	return output;
}

private int SetBoard(char[] characters)
{
	int length = characters.Count();
	board = new byte[rows, (columns * length)];
	int offset = 0;
	foreach (char character in characters)
	{
		int index = symbols.IndexOf(character);
		byte[,] symbol = AsTwoDimensionalArray(table[index], rows, columns);
		for (int row = 0; row < rows; row++)
		{
			for (int column = 0; column < columns; column++)
			{
				board[row, column + offset] = symbol[row, column];
			}
		}
		offset += columns;
	}
	return length;
}

private Windows.UI.Xaml.Shapes.Rectangle GetPixel(int row, int column)
{
	Windows.UI.Xaml.Shapes.Rectangle rect = 
		new Windows.UI.Xaml.Shapes.Rectangle()
	{
		Height = size,
		Width = size,
		Fill = Foreground,
		RadiusX = 2,
		RadiusY = 2,
		Opacity = 0,
		Margin = new Thickness(2)
	};
	rect.SetValue(Grid.ColumnProperty, column);
	rect.SetValue(Grid.RowProperty, row);
	return rect;
}

private void Setup()
{
	for (int row = 0; row < board.GetLength(0); row++)
	{
		for (int column = 0; column < board.GetLength(1); column++)
		{
			Windows.UI.Xaml.Shapes.Rectangle rect = 
				Display.Children.Cast<Windows.UI.Xaml.Shapes.Rectangle>()
				.FirstOrDefault(
				f => Grid.GetRow(f) == row 
				&& Grid.GetColumn(f) == column);
			rect.Opacity = board[row, column];
		}
	}
}

private void Layout(int length)
{
	int total = (columns * length);
	Display.Children.Clear();
	Display.RowDefinitions.Clear();
	Display.ColumnDefinitions.Clear();
	// Grid
	for (int row = 0; row < rows; row++)
	{
		Display.RowDefinitions.Add(new RowDefinition());
	}
	for (int column = 0; column < total; column++)
	{
		Display.ColumnDefinitions.Add(new ColumnDefinition());
	}
	// Layout
	for (int row = 0; row < rows; row++)
	{
		for (int column = 0; column < total; column++)
		{
			Display.Children.Add(GetPixel(row, column));
		}
	}
	Display.Height = Display.RowDefinitions.Count() * (size + 10);
	Display.Width = (Display.ColumnDefinitions.Count() * (size + 20)) / 2;
}

private void SetOutput(string content)
{
	char[] characters = content.ToCharArray();
	int length = SetBoard(characters);
	if (characters.Length != count)
	{
		Layout(characters.Length);
	}
	Setup();
}

public string Output
{
	get { return _output; }
	set
	{
		if (_output != value)
		{
			_output = value;
			SetOutput(_output);
		}
	}
}

Step 11

From the Menu choose Build and then Build Solution

vs2017-build

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 below enter the following XAML:

<local:Matrix x:Name="Display" HorizontalAlignment="Center" VerticalAlignment="Center"  Margin="50" Foreground="{ThemeResource AccentButtonBackground}" Loaded="Display_Loaded"/>

It should appear as such:

xaml-matrix-control

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:

private void Display_Loaded(object sender, RoutedEventArgs e)
{
	int count = 0;
	DispatcherTimer timer = new DispatcherTimer()
	{
		Interval = TimeSpan.FromMilliseconds(100)
	};
	timer.Tick += (object s, object args) =>
	{
		if (count > 150) count = 0;
		string format = (count < 100) ? "HH:mm:ss" : "dd/MM/yyyy";
		Display.Output = DateTime.Now.ToString(format);
		count++;
	};
	timer.Start();
}

It should then appear as such:

code-matrix-control

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 displaying a Matrix based Clock that will also alternate to show Time and then Date

run-matrix-control

Step 19

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Universal Windows Platform – Custom ComboBox

Step 1

Enable your device for Developer Mode, if not done already then in Windows 10, choose Start and then Settings

win10-settings

From Windows Setttings choose Update & security

win10-update

Then choose For developers and select Developer mode

win10-dev

Step 2

In Windows 10 you need to choose Start then Visual Studio 2017

vs2017-home

If this is not already Downloaded and Installed then Download Visual Studio Community 2017 and then select Run

vs2017-download

Once Visual Studio Community 2017 has been downloaded then you will need to Run the Visual Studio Installer

vs2017-install.png

Then select Continue to prepare the installation, once ready you then to select at least the Universal Windows Platform development option from Workloads in the Visual Studio Installer and then choose Install and follow any on-screen instructions

vs2017-workload

Step 3

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

vs2017-file-new-project

Step 4

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 5

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 6

In the Solution Explorer select App.xaml

vs2017-app

Step 7

From the Menu choose View and then Designer

vs2017-view-designer

Step 8

The XAML View will be displayed and in this above enter the following XAML:

<Application.Resources>
	<Style x:Key="CustomComboBox" TargetType="ComboBox">
		<Setter Property="Padding" Value="12,5,0,7"/>
		<Setter Property="MinWidth" Value="{ThemeResource ComboBoxThemeMinWidth}"/>
		<Setter Property="Foreground" Value="Gold"/>
		<Setter Property="Background" Value="{ThemeResource ComboBoxBackground}"/>
		<Setter Property="BorderBrush" Value="{ThemeResource ComboBoxBorderBrush}"/>
		<Setter Property="BorderThickness" Value="{ThemeResource ComboBoxBorderThemeThickness}"/>
		<Setter Property="TabNavigation" Value="Once"/>
		<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
		<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
		<Setter Property="ScrollViewer.HorizontalScrollMode" Value="Disabled"/>
		<Setter Property="ScrollViewer.VerticalScrollMode" Value="Auto"/>
		<Setter Property="ScrollViewer.IsVerticalRailEnabled" Value="True"/>
		<Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="False"/>
		<Setter Property="ScrollViewer.BringIntoViewOnFocusChange" Value="True"/>
		<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
		<Setter Property="HorizontalAlignment" Value="Left"/>
		<Setter Property="VerticalAlignment" Value="Top"/>
		<Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
		<Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
		<Setter Property="ItemsPanel">
			<Setter.Value>
				<ItemsPanelTemplate>
					<CarouselPanel/>
				</ItemsPanelTemplate>
			</Setter.Value>
		</Setter>
		<Setter Property="Template">
			<Setter.Value>
				<ControlTemplate TargetType="ComboBox">
					<Grid x:Name="LayoutRoot">
						<Grid.Resources>
							<Storyboard x:Key="OverlayOpeningAnimation">
								<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="Opacity">
									<DiscreteDoubleKeyFrame KeyTime="0:0:0" Value="0.0"/>
									<SplineDoubleKeyFrame KeySpline="0.1,0.9 0.2,1.0" KeyTime="0:0:0.383" Value="1.0"/>
								</DoubleAnimationUsingKeyFrames>
							</Storyboard>
							<Storyboard x:Key="OverlayClosingAnimation">
								<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="Opacity">
									<DiscreteDoubleKeyFrame KeyTime="0:0:0" Value="1.0"/>
									<SplineDoubleKeyFrame KeySpline="0.1,0.9 0.2,1.0" KeyTime="0:0:0.216" Value="0.0"/>
								</DoubleAnimationUsingKeyFrames>
							</Storyboard>
						</Grid.Resources>
						<Grid.ColumnDefinitions>
							<ColumnDefinition Width="*"/>
							<ColumnDefinition Width="32"/>
						</Grid.ColumnDefinitions>
						<Grid.RowDefinitions>
							<RowDefinition Height="Auto"/>
							<RowDefinition Height="*"/>
						</Grid.RowDefinitions>
						<VisualStateManager.VisualStateGroups>
							<VisualStateGroup x:Name="CommonStates">
								<VisualState x:Name="Normal"/>
								<VisualState x:Name="PointerOver">
									<Storyboard>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="Background">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ComboBoxBackgroundPointerOver}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="Background">
											<DiscreteObjectKeyFrame KeyTime="0" Value="GoldenRod"/>
										</ObjectAnimationUsingKeyFrames>
									</Storyboard>
								</VisualState>
								<VisualState x:Name="Pressed">
									<Storyboard>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="Background">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ComboBoxBackgroundPressed}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="Background">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ComboBoxBorderBrushPressed}"/>
										</ObjectAnimationUsingKeyFrames>
									</Storyboard>
								</VisualState>
								<VisualState x:Name="Disabled">
									<Storyboard>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="Background">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ComboBoxBackgroundDisabled}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="Background">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ComboBoxBorderBrushDisabled}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="HeaderContentPresenter">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ComboBoxForegroundDisabled}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ComboBoxForegroundDisabled}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="PlaceholderTextBlock">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ComboBoxForegroundDisabled}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="DropDownGlyph">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ComboBoxDropDownGlyphForegroundDisabled}"/>
										</ObjectAnimationUsingKeyFrames>
									</Storyboard>
								</VisualState>
							</VisualStateGroup>
							<VisualStateGroup x:Name="FocusStates">
								<VisualState x:Name="Focused">
									<Storyboard>
										<DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="HighlightBackground"/>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="HighlightBackground">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ComboBoxBackgroundBorderBrushFocused}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ComboBoxForegroundFocused}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="PlaceholderTextBlock">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ComboBoxForegroundFocused}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="DropDownGlyph">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ComboBoxDropDownGlyphForegroundFocused}"/>
										</ObjectAnimationUsingKeyFrames>
									</Storyboard>
								</VisualState>
								<VisualState x:Name="FocusedPressed">
									<Storyboard>
										<DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="HighlightBackground"/>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ComboBoxForegroundFocusedPressed}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="PlaceholderTextBlock">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ComboBoxPlaceHolderForegroundFocusedPressed}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="DropDownGlyph">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ComboBoxDropDownGlyphForegroundFocusedPressed}"/>
										</ObjectAnimationUsingKeyFrames>
									</Storyboard>
								</VisualState>
								<VisualState x:Name="Unfocused"/>
								<VisualState x:Name="PointerFocused"/>
								<VisualState x:Name="FocusedDropDown">
									<Storyboard>
										<ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="Visibility" Storyboard.TargetName="PopupBorder">
											<DiscreteObjectKeyFrame KeyTime="0">
												<DiscreteObjectKeyFrame.Value>
													<Visibility>Visible</Visibility>
												</DiscreteObjectKeyFrame.Value>
											</DiscreteObjectKeyFrame>
										</ObjectAnimationUsingKeyFrames>
									</Storyboard>
								</VisualState>
							</VisualStateGroup>
							<VisualStateGroup x:Name="DropDownStates">
								<VisualState x:Name="Opened">
									<Storyboard>
										<SplitOpenThemeAnimation ClosedTargetName="ContentPresenter" 
										OffsetFromCenter="{Binding TemplateSettings.DropDownOffset, RelativeSource={RelativeSource Mode=TemplatedParent}}" 
										OpenedTargetName="PopupBorder" OpenedLength="{Binding TemplateSettings.DropDownOpenedHeight, RelativeSource={RelativeSource Mode=TemplatedParent}}"/>
									</Storyboard>
								</VisualState>
								<VisualState x:Name="Closed">
									<Storyboard>
										<SplitCloseThemeAnimation ClosedTargetName="ContentPresenter" 
										OffsetFromCenter="{Binding TemplateSettings.DropDownOffset, RelativeSource={RelativeSource Mode=TemplatedParent}}" 
										OpenedTargetName="PopupBorder" OpenedLength="{Binding TemplateSettings.DropDownOpenedHeight, RelativeSource={RelativeSource Mode=TemplatedParent}}"/>
									</Storyboard>
								</VisualState>
							</VisualStateGroup>
						</VisualStateManager.VisualStateGroups>
						<Border x:Name="Background" BorderBrush="Salmon" BorderThickness="{TemplateBinding BorderThickness}" 
						Background="LightSalmon" Grid.ColumnSpan="2" Grid.Row="1" CornerRadius="15"/>
						<Border x:Name="HighlightBackground" BorderBrush="Gold" BorderThickness="{TemplateBinding BorderThickness}" 
						Background="{ThemeResource ComboBoxBackgroundUnfocused}" Grid.ColumnSpan="2" Opacity="0" Grid.Row="1" CornerRadius="15"/>
						<ContentPresenter x:Name="ContentPresenter" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
						Margin="{TemplateBinding Padding}" Grid.Row="1" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" CornerRadius="15">
							<TextBlock x:Name="PlaceholderTextBlock" Foreground="{ThemeResource ComboBoxPlaceHolderForeground}" 
							Text="{TemplateBinding PlaceholderText}"/>
						</ContentPresenter>
						<FontIcon x:Name="DropDownGlyph" AutomationProperties.AccessibilityView="Raw" Grid.Column="1" Foreground="Gold" 
						FontSize="12" FontFamily="{ThemeResource SymbolThemeFontFamily}" Glyph="" HorizontalAlignment="Right" 
						IsHitTestVisible="False" Margin="0,10,10,10" Grid.Row="1" VerticalAlignment="Center"/>
						<Popup x:Name="Popup">
							<Border x:Name="PopupBorder" BorderBrush="Salmon" 
							BorderThickness="{ThemeResource ComboBoxDropdownBorderThickness}" 
							Background="LightSalmon" HorizontalAlignment="Stretch" 
							Margin="0,-1,0,-1" CornerRadius="15">
								<ScrollViewer x:Name="ScrollViewer" AutomationProperties.AccessibilityView="Raw" 
								BringIntoViewOnFocusChange="{TemplateBinding ScrollViewer.BringIntoViewOnFocusChange}" 
								Foreground="{ThemeResource ComboBoxDropDownForeground}" 
								HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}" 
								HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}" 
								IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}" 
								IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}" 
								IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}" 
								MinWidth="{Binding TemplateSettings.DropDownContentMinWidth, RelativeSource={RelativeSource Mode=TemplatedParent}}" 
								VerticalSnapPointsType="OptionalSingle" VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}" 
								VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}" VerticalSnapPointsAlignment="Near" ZoomMode="Disabled">
									<ItemsPresenter Margin="{ThemeResource ComboBoxDropdownContentMargin}"/>
								</ScrollViewer>
							</Border>
						</Popup>
					</Grid>
				</ControlTemplate>
			</Setter.Value>
		</Setter>
	</Style>
</Application.Resources>

Step 9

From the Solution Explorer select MainPage.xaml

vs2017-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 below enter the following XAML:

<ComboBox SelectedIndex="0" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource CustomComboBox}">
	<ComboBoxItem Content="ComboBox"/>
	<ComboBoxItem Content="One"/>
	<ComboBoxItem Content="Two"/>
	<ComboBoxItem Content="Three"/>
	<ComboBoxItem Content="Four"/>
</ComboBox>

It should appear as such:

xaml-custom-combobox

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

run-custom-combobox

Step 14

After the Application has started running you can then select ComboBox if not already and then select one of the items from the ComboBox

ran-custom-combobox

Step 15

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Universal Windows Platform – Custom TextBox

Step 1

Enable your device for Developer Mode, if not done already then in Windows 10, choose Start and then Settings

win10-settings

From Windows Setttings choose Update & security

win10-update

Then choose For developers and select Developer mode

win10-dev

Step 2

In Windows 10 you need to choose Start then Visual Studio 2017

vs2017-home

If this is not already Downloaded and Installed then Download Visual Studio Community 2017 and then select Run

vs2017-download

Once Visual Studio Community 2017 has been downloaded then you will need to Run the Visual Studio Installer

vs2017-install.png

Then select Continue to prepare the installation, once ready you then to select at least the Universal Windows Platform development option from Workloads in the Visual Studio Installer and then choose Install and follow any on-screen instructions

vs2017-workload

Step 3

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

vs2017-file-new-project

Step 4

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 5

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 6

In the Solution Explorer select App.xaml

vs2017-app

Step 7

From the Menu choose View and then Designer

vs2017-view-designer

Step 8

The XAML View will be displayed and in this above enter the following XAML:

<Application.Resources>
	<Style x:Key="CustomTextBox" TargetType="TextBox">
		<Setter Property="MinWidth" Value="{ThemeResource TextControlThemeMinWidth}"/>
		<Setter Property="MinHeight" Value="{ThemeResource TextControlThemeMinHeight}"/>
		<Setter Property="Foreground" Value="Gold"/>
		<Setter Property="Background" Value="{ThemeResource TextControlBackground}"/>
		<Setter Property="SelectionHighlightColor" Value="{ThemeResource TextControlSelectionHighlightColor}"/>
		<Setter Property="BorderThickness" Value="2"/>
		<Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
		<Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
		<Setter Property="ScrollViewer.HorizontalScrollMode" Value="Auto"/>
		<Setter Property="ScrollViewer.VerticalScrollMode" Value="Auto"/>
		<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Hidden"/>
		<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Hidden"/>
		<Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="False"/>
		<Setter Property="Padding" Value="{ThemeResource TextControlThemePadding}"/>
		<Setter Property="Template">
			<Setter.Value>
				<ControlTemplate TargetType="TextBox">
					<Grid>
						<Grid.ColumnDefinitions>
							<ColumnDefinition Width="*"/>
							<ColumnDefinition Width="Auto"/>
						</Grid.ColumnDefinitions>
						<Grid.RowDefinitions>
							<RowDefinition Height="Auto"/>
							<RowDefinition Height="*"/>
						</Grid.RowDefinitions>
						<VisualStateManager.VisualStateGroups>
							<VisualStateGroup x:Name="CommonStates">
								<VisualState x:Name="Disabled">
									<Storyboard>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="HeaderContentPresenter">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlHeaderForegroundDisabled}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="BorderElement">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundDisabled}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="BorderElement">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushDisabled}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentElement">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundDisabled}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="PlaceholderTextContentPresenter">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundDisabled}"/>
										</ObjectAnimationUsingKeyFrames>
									</Storyboard>
								</VisualState>
								<VisualState x:Name="Normal"/>
								<VisualState x:Name="PointerOver">
									<Storyboard>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="BorderElement">
											<DiscreteObjectKeyFrame KeyTime="0" Value="GoldenRod"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="BorderElement">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundPointerOver}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="PlaceholderTextContentPresenter">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundPointerOver}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentElement">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundPointerOver}"/>
										</ObjectAnimationUsingKeyFrames>
									</Storyboard>
								</VisualState>
								<VisualState x:Name="Focused">
									<Storyboard>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="PlaceholderTextContentPresenter">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundFocused}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="BorderElement">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundFocused}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="BorderElement">
											<DiscreteObjectKeyFrame KeyTime="0" Value="Gold"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentElement">
											<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundFocused}"/>
										</ObjectAnimationUsingKeyFrames>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="RequestedTheme" Storyboard.TargetName="ContentElement">
											<DiscreteObjectKeyFrame KeyTime="0" Value="Light"/>
										</ObjectAnimationUsingKeyFrames>
									</Storyboard>
								</VisualState>
							</VisualStateGroup>
						</VisualStateManager.VisualStateGroups>
						<Border x:Name="BorderElement" BorderBrush="Salmon" BorderThickness="{TemplateBinding BorderThickness}" Background="LightSalmon" Grid.ColumnSpan="2" Grid.Row="1" Grid.RowSpan="1" CornerRadius="15"/>
						<ScrollViewer x:Name="ContentElement" AutomationProperties.AccessibilityView="Raw" HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}" 
						HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}" IsTabStop="False" IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}" 
						IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}" IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}" Margin="{TemplateBinding BorderThickness}" 
						Padding="{TemplateBinding Padding}" Grid.Row="1" VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}" VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}" 
						ZoomMode="Disabled"/>
						<ContentPresenter x:Name="PlaceholderTextContentPresenter" Grid.ColumnSpan="2" Content="{TemplateBinding PlaceholderText}" Foreground="Gold" IsHitTestVisible="False" Margin="{TemplateBinding BorderThickness}" 
						Padding="{TemplateBinding Padding}" Grid.Row="1" TextWrapping="{TemplateBinding TextWrapping}"/>
					</Grid>
				</ControlTemplate>
			</Setter.Value>
		</Setter>
	</Style>
</Application.Resources>

Step 9

From the Solution Explorer select MainPage.xaml

vs2017-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 below enter the following XAML:

<TextBox Text="TextBox" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource CustomTextBox}"/>

It should appear as such:

xaml-custom-textbox

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

run-custom-textbox

Step 14

After the Application has started running you can then select TextBox if not already and then type in some Text then you can deselect the TextBox once finished

ran-custom-textbox

Step 15

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Universal Windows Platform – Contacts App

Step 1

Enable your device for Developer Mode, if not done already then in Windows 10, choose Start and then Settings

win10-settings

From Windows Setttings choose Update & security

win10-update

Then choose For developers and select Developer mode

win10-dev

Step 2

In Windows 10 you need to choose Start then Visual Studio 2017

vs2017-home

If this is not already Downloaded and Installed then Download Visual Studio Community 2017 and then select Run

vs2017-download

Once Visual Studio Community 2017 has been downloaded then you will need to Run the Visual Studio Installer

vs2017-install.png

Then select Continue to prepare the installation, once ready you then to select at least the Universal Windows Platform development option from Workloads in the Visual Studio Installer and then choose Install and follow any on-screen instructions

vs2017-workload

Step 3

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

vs2017-file-new-project

Step 4

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 5

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 6

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 7

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 8

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.Contacts;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;

public class Item
{
    public string Id { get; set; }
    public string Address { get; set; }
    public string DisplayName { get; set; }
}

public class Library
{
    private const string contacts_list = "Contacts App";

    private async Task<ContactStore> Store()
    {
        return await ContactManager.RequestStoreAsync(ContactStoreAccessType.AppContactsReadWrite);
    }

    private InputScope Scope(InputScopeNameValue value)
    {
        InputScope scope = new InputScope();
        InputScopeName name = new InputScopeName()
        {
            NameValue = value
        };
        scope.Names.Add(name);
        return scope;
    }

    private async Task<Contact> Dialog(Contact contact)
    {
        Thickness margin = new Thickness(5);
        TextBox firstname = new TextBox()
        {
            Text = contact.FirstName,
            Margin = margin,
            PlaceholderText = "First Name"
        };
        TextBox lastname = new TextBox()
        {
            Text = contact.LastName,
            Margin = margin,
            PlaceholderText = "Last Name"
        };
        TextBox email = new TextBox()
        {
            Text = contact?.Emails?.FirstOrDefault()?.Address ?? string.Empty,
            Margin = margin,
            PlaceholderText = "Email Address",
            InputScope = Scope(InputScopeNameValue.EmailSmtpAddress)         
        };
        StackPanel panel = new StackPanel()
        {
            Orientation = Orientation.Vertical
        };
        panel.Children.Add(firstname);
        panel.Children.Add(lastname);
        panel.Children.Add(email);
        ContentDialog dialog = new ContentDialog()
        {
            Title = "Contact",
            PrimaryButtonText = "Save",
            CloseButtonText = "Cancel",
            Content = panel
        };
        ContentDialogResult result = await dialog.ShowAsync();
        if (result == ContentDialogResult.Primary)
        {
            contact.FirstName = firstname.Text;
            contact.LastName = lastname.Text;
            contact.Emails.Add(new ContactEmail() { Address = email.Text });
            return contact;
        }
        return null;
    }

    private async Task<ContactList> GetAsync()
    {
        ContactList result = null;
        ContactStore store = await Store();
        if (store != null)
        {
            IReadOnlyList<ContactList> list = await store.FindContactListsAsync();
            if(list.Count == 0)
            {
                result = await store.CreateContactListAsync(contacts_list);
            }
            else
            {
                result = list.FirstOrDefault(s => s.DisplayName == contacts_list);
            }
        }
        return result;
    }

    private async Task<IReadOnlyList<Contact>> ListContactsAsync()
    {
        ContactStore store = await Store();
        if (store != null)
        {
            ContactList list = await GetAsync();
            if (list != null)
            {
                ContactReader reader = list.GetContactReader();
                if (reader != null)
                {
                    ContactBatch batch = await reader.ReadBatchAsync();
                    if (batch != null)
                    {
                        return batch.Contacts;
                    }
                }
            }
        }
        return null;
    }

    private async Task<Contact> GetContactAsync(string id)
    {
        ContactList list = await GetAsync();
        if (list != null)
        {
            return await list.GetContactAsync(id);
        }
        return null;
    }

    public async Task<List<Item>> ListAsync()
    {
        List<Item> results = new List<Item>();
        IReadOnlyList<Contact> contacts = await ListContactsAsync();
        foreach (Contact contact in contacts)
        {
            results.Add(new Item
            {
                Id = contact.Id,
                DisplayName = contact.DisplayName,
                Address = contact?.Emails?.FirstOrDefault()?.Address
            });
        }
        return results;
    }

    public async Task<bool> Add(AppBarButton button)
    {
        Contact contact = await Dialog(new Contact());
        if(contact != null)
        {
            ContactList list = await GetAsync();
            if(list != null)
            {
               await list.SaveContactAsync(contact);
               return true;
            }
        }
        return false;
    }

    public async Task<bool> Edit(AppBarButton button)
    {
        Item item = (Item)button.Tag;
        Contact contact = await GetContactAsync(item.Id);
        if (contact != null)
        {
            contact = await Dialog(contact);
            if (contact != null)
            {
                ContactList list = await GetAsync();
                if (list != null)
                {
                    await list.SaveContactAsync(contact);
                    return true;
                }
            }
        }
        return false;
    }

    public async Task<bool> Delete(AppBarButton button)
    {
        Item item = (Item)button.Tag;
        Contact contact = await GetContactAsync(item.Id);
        if(contact != null)
        {
            ContactList list = await GetAsync();
            if (list != null)
            {
                await list.DeleteContactAsync(contact);
                return true;
            }
        }
        return false;
    }
}

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 below enter the following XAML:

<Grid>
	<Grid.RowDefinitions>
		<RowDefinition Height="*"/>
		<RowDefinition Height="Auto"/>
	</Grid.RowDefinitions>
	<CommandBar Grid.Row="1">
		<AppBarButton Name="Add" Icon="Add" Label="New" 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="40*"/>
						<ColumnDefinition Width="40*"/>
						<ColumnDefinition Width="Auto"/>
					</Grid.ColumnDefinitions>
					<Grid Padding="5" Grid.Column="0" Background="{ThemeResource AccentButtonBackground}">
						<TextBlock Text="{Binding DisplayName}" VerticalAlignment="Center"
							Foreground="{ThemeResource AccentButtonForeground}"/>
					</Grid>
					<Grid Padding="5" Grid.Column="1" Background="{ThemeResource AccentButtonForeground}">
						<TextBlock Text="{Binding Address}" VerticalAlignment="Center"
							Foreground="{ThemeResource AccentButtonBackground}"/>
					</Grid>
					<StackPanel Grid.Column="3" 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>
</Grid>

It should appear as such:

xaml-contacts-app

Step 12

From the Menu choose View and then Code

vs2017-view-code

Step 13

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)
{
	Display.ItemsSource = await library.ListAsync();
}

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

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

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

It should then appear as such:

code-contacts-app

Step 14

Then in the Solution Explorer select Package.appxmanifest

vs2017-library-manifest

Step 15

Then from the Menu choose View and then Designer

vs2017-view-designer

Step 16

The Design View will be displayed for the Package.appxmanifest, then select the Capabilities Tab and Tick the Contacts option from the list of Capabilities

manifest-contact-app

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-contacts-app

Step 19

After the Application has started running you can then select Add to create a new Contact, this will display a Dialog where you can enter the First Name, Last Name and Email Address for a Contact. Contacts added will be displayed in the List where you can Edit or Delete them.

ran-contacts-app

Step 20

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Universal Windows Platform – Calendar App

Step 1

Enable your device for Developer Mode, if not done already then in Windows 10, choose Start and then Settings

win10-settings

From Windows Setttings choose Update & security

win10-update

Then choose For developers and select Developer mode

win10-dev

Step 2

In Windows 10 you need to choose Start then Visual Studio 2017

vs2017-home

If this is not already Downloaded and Installed then Download Visual Studio Community 2017 and then select Run

vs2017-download

Once Visual Studio Community 2017 has been downloaded then you will need to Run the Visual Studio Installer

vs2017-install.png

Then select Continue to prepare the installation, once ready you then to select at least the Universal Windows Platform development option from Workloads in the Visual Studio Installer and then choose Install and follow any on-screen instructions

vs2017-workload

Step 3

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

vs2017-file-new-project

Step 4

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 5

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 6

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 7

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 8

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.Appointments;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

public class Item
{
    public string Id { get; set; }
    public DateTimeOffset StartTime { get; set; }
    public string When { get { return StartTime.ToString("dd MMMM yyyy HH:mm:ss"); } }
    public string Subject { get; set; }
    public string Details { get; set; }
}

public class Library
{
    private const string appointment_calendar = "Calendar App";

    private async Task<AppointmentStore> Store()
    {
        return await AppointmentManager.RequestStoreAsync(AppointmentStoreAccessType.AppCalendarsReadWrite);
    }

    private DateTime GetDateTime(DateTimeOffset date, TimeSpan time)
    {
        return new DateTime(date.Year, date.Month, date.Day, time.Hours, time.Minutes, time.Seconds);
    }

    private async Task<Appointment> Dialog(Appointment appointment, ResourceDictionary resources)
    {
        Thickness margin = new Thickness(5);
        DatePicker date = new DatePicker()
        {
            Date = appointment.StartTime,
            Margin = margin,
            HorizontalAlignment = HorizontalAlignment.Stretch
        };
        TimePicker time = new TimePicker()
        {
            Time = appointment.StartTime.TimeOfDay,
            Margin = margin,
            HorizontalAlignment = HorizontalAlignment.Stretch
        };
        TextBox subject = new TextBox()
        {
            Text = appointment.Subject,
            Margin = margin,
            PlaceholderText = "Subject"
        };
        TextBox details = new TextBox()
        {
            Text = appointment.Details,
            Margin = margin,
            PlaceholderText = "Details",
            AcceptsReturn = true,
            TextWrapping = TextWrapping.Wrap,
            Height = (double)resources["SearchBoxSuggestionPopupThemeMaxHeight"]
        };
        StackPanel panel = new StackPanel()
        {
            Orientation = Orientation.Vertical
        };
        panel.Children.Add(date);
        panel.Children.Add(time);
        panel.Children.Add(subject);
        panel.Children.Add(details);
        ContentDialog dialog = new ContentDialog()
        {
            Title = "Appointment",
            PrimaryButtonText = "Save",
            CloseButtonText = "Cancel",
            Content = panel
        };
        ContentDialogResult result = await dialog.ShowAsync();
        if (result == ContentDialogResult.Primary)
        {
            appointment.StartTime = GetDateTime(date.Date, time.Time);
            appointment.Subject = subject.Text;
            appointment.Details = details.Text;
            return appointment;
        }
        return null;
    }

    private async Task<AppointmentCalendar> GetAsync()
    {
        AppointmentCalendar result = null;
        AppointmentStore store = await Store();
        if (store != null)
        {
            IReadOnlyList<AppointmentCalendar> list = await store.FindAppointmentCalendarsAsync();
            if (list.Count == 0)
            {
                result = await store.CreateAppointmentCalendarAsync(appointment_calendar);
            }
            else
            {
                result = list.FirstOrDefault(s => s.DisplayName == appointment_calendar);
            }
        }
        return result;
    }

    private async Task<IReadOnlyList<Appointment>> ListAppointmentsAsync(DateTimeOffset start, TimeSpan range)
    {
        AppointmentStore store = await Store();
        if (store != null)
        {
            AppointmentCalendar calendar = await GetAsync();
            if (calendar != null)
            {
                return await calendar.FindAppointmentsAsync(start, range);
            }
        }
        return null;
    }

    private async Task<Appointment> GetAppointmentAsync(string id)
    {
        AppointmentCalendar calendar = await GetAsync();
        if (calendar != null)
        {
            return await calendar.GetAppointmentAsync(id);
        }
        return null;
    }

    public void Start(ref CalendarDatePicker picker)
    {
        DateTime now = DateTime.Now;
        if (picker.Date == null)
        {
            picker.Date = GetDateTime(DateTime.Now, new TimeSpan(0, 0, 0));
        }
    }

    public async Task<List<Item>> ListAsync(DateTimeOffset start)
    {
        DateTimeOffset finish = start.AddMonths(1);
        TimeSpan range = finish - start;
        List<Item> results = new List<Item>();
        IReadOnlyList<Appointment> appointments = await ListAppointmentsAsync(start, range);
        foreach (Appointment appointment in appointments)
        {
            results.Add(new Item()
            {
                Id = appointment.LocalId,
                StartTime = appointment.StartTime,
                Subject = appointment.Subject,
                Details = appointment.Details
            });
        }
        return results;
    }

    public async Task<bool> Add(AppBarButton button, ResourceDictionary resources)
    {
        Appointment appointment = await Dialog(new Appointment(), resources);
        if (appointment != null)
        {
            AppointmentCalendar calendar = await GetAsync();
            if (calendar != null)
            {
                await calendar.SaveAppointmentAsync(appointment);
                return true;
            }
        }
        return false;
    }

    public async Task<bool> Edit(AppBarButton button, ResourceDictionary resources)
    {
        Item item = (Item)button.Tag;
        Appointment appointment = await GetAppointmentAsync(item.Id);
        if (appointment != null)
        {
            appointment = await Dialog(appointment, resources);
            if (appointment != null)
            {
                AppointmentCalendar calendar = await GetAsync();
                if (calendar != null)
                {
                    await calendar.SaveAppointmentAsync(appointment);
                    return true;
                }
            }
        }
        return false;
    }

    public async Task<bool> Delete(AppBarButton button)
    {
        Item item = (Item)button.Tag;
        Appointment appointment = await GetAppointmentAsync(item.Id);
        if (appointment != null)
        {
            AppointmentCalendar calendar = await GetAsync();
            if (calendar != null)
            {
                await calendar.DeleteAppointmentAsync(item.Id);
                return true;
            }
        }
        return false;
    }
}

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 below enter the following XAML:

<Grid>
	<Grid.RowDefinitions>
		<RowDefinition Height="Auto"/>
		<RowDefinition Height="*"/>
		<RowDefinition Height="Auto"/>
	</Grid.RowDefinitions>
	<CommandBar Grid.Row="2">
		<AppBarButton Name="Add" Icon="Add" Label="New" Click="Add_Click"/>
	</CommandBar>
	<CalendarDatePicker Grid.Row="0" Name="Picker" HorizontalAlignment="Stretch"
		 PlaceholderText="Display Appointments From" DateChanged="Picker_DateChanged"/>
	<ListBox Grid.Row="1" 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="40*"/>
						<ColumnDefinition Width="40*"/>
						<ColumnDefinition Width="Auto"/>
					</Grid.ColumnDefinitions>
					<Grid Padding="5" Grid.Column="0" Background="{ThemeResource AccentButtonBackground}">
						<TextBlock Text="{Binding When}" VerticalAlignment="Center"
							Foreground="{ThemeResource AccentButtonForeground}"/>
					</Grid>
					<Grid Padding="5" Grid.Column="1" Background="{ThemeResource AccentButtonForeground}">
						<TextBlock Text="{Binding Subject}" VerticalAlignment="Center"
							Foreground="{ThemeResource AccentButtonBackground}"/>
					</Grid>
					<StackPanel Grid.Column="3" 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>
</Grid>

It should appear as such:

xaml-calendar-app

Step 12

From the Menu choose View and then Code

vs2017-view-code

Step 13

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

Library library = new Library();

private async void Picker_DateChanged(CalendarDatePicker sender, CalendarDatePickerDateChangedEventArgs args)
{
	Display.ItemsSource = await library.ListAsync((DateTimeOffset)Picker.Date);
}

private async void Display_Loaded(object sender, RoutedEventArgs e)
{
	library.Start(ref Picker);
	Display.ItemsSource = await library.ListAsync((DateTimeOffset)Picker.Date);
}

private async void Add_Click(object sender, RoutedEventArgs e)
{
	if(await library.Add(Add, App.Current.Resources))
	{
		Display.ItemsSource = await library.ListAsync((DateTimeOffset)Picker.Date);
	}
}

private async void Edit_Click(object sender, RoutedEventArgs e)
{
	if (await library.Edit((AppBarButton)sender, App.Current.Resources))
	{
		Display.ItemsSource = await library.ListAsync((DateTimeOffset)Picker.Date);
	}
}

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

It should then appear as such:

code-calendar-app

Step 14

Then in the Solution Explorer select Package.appxmanifest

vs2017-library-manifest

Step 15

Then from the Menu choose View and then Designer

vs2017-view-designer

Step 16

The Design View will be displayed for the Package.appxmanifest, then select the Capabilities Tab and Tick the Appointments option from the list of Capabilities

manifest-calendar-app

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-calendar-app

Step 19

After the Application has started running you can then select Add to create a new Appointment, this will display a Dialog where you can enter the Date, Time, Subject and Details for an Appointment. Appointments added will be displayed in the List where you can Edit or Delete them and you can control the date range to start showing Appointments from with the CalendarDatePicker at the top.

ran-calendar-app

Step 20

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License