Universal Windows Platform – Lights Control

Lights Control demonstrates how to create a Lights Control to display indicator lights – in this case was used to display the sequence of lights for a UK Traffic Light.

Step 1

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

vs2017

Step 2

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

vs2017-file-new-project

Step 3

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

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10, version 1803 (10.0; Build 17134) which is the April 2018 Update and the Minimum Version to be the same.

vs2017-target-platform

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

Step 5

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

vs2017-project-add-new-item

Step 6

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

vs2017-add-new-item-library

Step 7

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

using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;

namespace LightsControl
{
    public class Light : Grid, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public static readonly DependencyProperty ForegroundProperty =
        DependencyProperty.Register("Foreground", typeof(Brush),
        typeof(Light), new PropertyMetadata(new SolidColorBrush(Colors.Black)));

        public static readonly DependencyProperty SizeProperty =
        DependencyProperty.Register("Size", typeof(double),
        typeof(Light), new PropertyMetadata((double)100));

        public static readonly DependencyProperty OffProperty =
        DependencyProperty.Register("Off", typeof(Visibility),
        typeof(Light), new PropertyMetadata(Visibility.Collapsed));

        public Brush Foreground
        {
            get { return (Brush)GetValue(ForegroundProperty); }
            set
            {
                SetValue(ForegroundProperty, value);
                NotifyPropertyChanged("Foreground");
            }
        }

        public double Size
        {
            get { return (double)GetValue(SizeProperty); }
            set
            {
                SetValue(SizeProperty, value);
                NotifyPropertyChanged("Size");
            }
        }

        public Visibility Off
        {
            get { return (Visibility)GetValue(OffProperty); }
            set
            {
                SetValue(OffProperty, value);
                NotifyPropertyChanged("Off");
            }
        }

        public Light()
        {
            this.Margin = new Thickness(5);
            Ellipse element = new Ellipse()
            {
                Stretch = Stretch.Fill,
                Height = Size,
                Width = Size
            };
            element.SetBinding(Ellipse.FillProperty, new Binding()
            {
                Source = this,
                Path = new PropertyPath("Foreground"),
                Mode = BindingMode.TwoWay
            });
            Ellipse overlay = new Ellipse()
            {
                Fill = new SolidColorBrush(Colors.Black),
                Stretch = Stretch.Fill,
                Opacity = 0.75,
                Height = Size,
                Width = Size
            };
            overlay.SetBinding(Ellipse.VisibilityProperty, new Binding()
            {
                Source = this,
                Path = new PropertyPath("Off"),
                Mode = BindingMode.TwoWay
            });
            this.Children.Add(element);
            this.Children.Add(overlay);
        }

        public bool IsOn
        {
            get { return Off == Visibility.Collapsed; }
            set
            {
                Off = value ? Visibility.Collapsed : Visibility.Visible;
                NotifyPropertyChanged("IsOn");
                NotifyPropertyChanged("Off");
            }
        }
    }

    public class Lights : StackPanel
    {
        private Light _red = new Light { Foreground = new SolidColorBrush(Colors.Red) };
        private Light _orange = new Light { Foreground = new SolidColorBrush(Colors.Orange) };
        private Light _green = new Light { Foreground = new SolidColorBrush(Colors.Green) };

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

        public Lights()
        {
            this.Orientation = Orientation.Vertical;
            this.Children.Add(_red);
            this.Children.Add(_orange);
            this.Children.Add(_green);
        }

        public async void Traffic()
        {
            _red.IsOn = false;
            _orange.IsOn = false;
            _green.IsOn = true;
            await Delay();
            _green.IsOn = false;
            await Delay();
            _orange.IsOn = true;
            await Delay();
            _orange.IsOn = false;
            await Delay();
            _red.IsOn = true;
            await Delay();
            _red.IsOn = true;
            await Delay();
            _orange.IsOn = true;
            await Delay();
            _red.IsOn = false;
            _orange.IsOn = false;
            _green.IsOn = true;
            await Delay();
        }
    }
}

There is a Light Class which implements the INotifyPropertyChanged Interface and contains a NotifyPropertyChanged Method to allow the Control to respond to updates, there are DependencyProperty and Properties for Foreground, Size and Off – this indicates if the Light should be enabled or not. The Light Constructor is used to create the look-and-feel of the Light itself and there is an IsOn Property to set the Off Property accordingly.

The Lights Class extends a StackPanel with three Light Controls within and a Delay Method which will be used to pause any output and a Traffic Method which contains the whole sequence for a traffic light – based on the UK traffic light sequence.

Step 8

Once done select from the Menu, Build, then Build Solution

vs2017-build-build-solution

Step 9

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library

Step 10

From the Menu choose View and then Designer

vs2017-view-designer

Step 11

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

<Viewbox>
	<local:Lights Margin="50" x:Name="Display" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Viewbox>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Icon="Play" Label="Play" Click="Play_Click"/>
</CommandBar>

The MainPage has the Lights Control itself along with a CommandBar with an AppBarButton to trigger the Play_Click Event.

Step 12

From the Menu choose View and then Code

vs2017-view-code

Step 13

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

private void Play_Click(object sender, RoutedEventArgs e)
{
	Display.Traffic();
}

Below the MainPage() Method there is the Play_Click Event Handler which triggers the Traffic Method of the Lights Control.

Step 14

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

vs2017-local-machine

Step 15

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

ran-lights-control

Step 16

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

vs2017-close

The Control is used to cycle through the light sequence from a UK Traffic light to demonstrate the principle of using the lights and to show they update accordingly and it could be expanded upon to display differently or as-is with more combinations of lights or appear more like traffic lights or even less like them to represent something else.

Creative Commons License

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s