更新时间:2023-02-26 17:56:06
我认为您有一个好的开始;计时器太多了.我正在尝试学习WPF,我认为这将是一个快速的实践项目.请注意,在XAML中,我从打开红灯开始.我稍微改变了颜色以获得更多的对比度(老眼睛). 在代码中,我减少了一个计时器,并使用if语句检查当前颜色.请注意,我确实保留了更短的橙色灯时间.
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>
这是C#代码...
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);
}
}
}