I have simple program using C# with WPF and when the program initializes I want the button color to become green and after 1 second become red. But when I use my program with Thread.Sleep(1000), it does not become red after 1 second. This might show I know something fundamentally wrong here. Below is the entire code I tried:
<Window x:Class="TestEventHandler.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:TestEventHandler"
mc:Ignorable="d"
Title="MainWindow" Height="250" Width="250">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="7*" />
<ColumnDefinition Width="389*"/>
</Grid.ColumnDefinitions>
<Button Grid.Row="0" Grid.Column="0" x:Name="MyButton" Grid.ColumnSpan="2" Click="MyButton_Click">MyButton</Button>
<Label Grid.Row="1" Grid.Column="0" x:Name="MyLabel" Grid.ColumnSpan="2" HorizontalContentAlignment="Center" VerticalContentAlignment="Center">MyLabel</Label>
</Grid>
</Window>
And here is the program logic:
using System.Threading;
using System.Windows;
using System.Windows.Media;
namespace TestEventHandler
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void MyButton_Click(object sender, RoutedEventArgs e)
{
MyLabel.Background = Brushes.Red;
Thread.Sleep(1000);
MyLabel.Background = Brushes.Green;
}
}
}
How can it be done that when the program initializes the button is green and the a second later the button color becomes red? What is a good and stable practice for that? Should I use Stopwatch?