Timer for traffic lights c#

做~自己de王妃 提交于 2019-12-02 13:23:37

I think you had a good start; just too many timers. I am trying to learn WPF and I thought this would be a quick project to practice on. Notice in the XAML, I started with the Red Light on. I changed the colors a bit to get more contrast (old eyes.) In the code I cut back to one timer and check the current colors with the if statements. Notice, I did preserve the shorter time for the Orange light.

<Window x:Class="StopLight.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:StopLight"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="200">
    <Grid>
        <Border BorderThickness ="5" Height="100" Width="50" BorderBrush="Black">
            <StackPanel>
                <Ellipse x:Name="RedLight" Fill="Red"  Height="30" Width="30" />
                <Ellipse x:Name="OrangeLight" Fill="PaleGoldenrod"  Height="30" Width="30"  />
                <Ellipse x:Name="GreenLight" Fill="PaleGreen"  Height="30" Width="30"  />
            </StackPanel>
        </Border>
    </Grid>
</Window>

And here is the C# code...

public partial class MainWindow : Window
    {
        DispatcherTimer disTime = new DispatcherTimer();
        public MainWindow()
        {
            InitializeComponent();
            disTime.Interval = new TimeSpan(0, 0, 10);
            disTime.Tick += disTime_Tick;
            disTime.Start();
        }
        private void disTime_Tick(object sender, EventArgs e)
        {
            if (RedLight.Fill == Brushes.Red)
            {
                RedLight.Fill = Brushes.PaleVioletRed;
                GreenLight.Fill = Brushes.Green;
            }
            else if (GreenLight.Fill == Brushes.Green)
            {
                GreenLight.Fill = Brushes.PaleGreen;
                OrangeLight.Fill = Brushes.Orange;
                disTime.Interval = new TimeSpan(0, 0, 5);
            }
            else if (OrangeLight.Fill ==Brushes.Orange)
            {
                OrangeLight.Fill = Brushes.PaleGoldenrod;
                RedLight.Fill = Brushes.Red;
                disTime.Interval = new TimeSpan(0, 0, 10);
            }
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!