我一直在学习WPF。我尝试在我的WPF应用程序中使用线程,但我想我错过了一些东西。
我在窗口放了一个按钮和一个标签。如果我按下按钮,我希望标签改变它的背景颜色...... 2秒后,设置原始背景颜色。
这是XAML和我一直在尝试的代码。
MainWindow.XAML
<Window x:Class="UITest.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:UITest"
mc:Ignorable="d"
Title="MainWindow" Height="519" Width="656">
<StackPanel>
<Button x:Name="button1" Width="60" Height="30" Content="Button" Margin="10 10 0 0" BorderThickness="0" BorderBrush="{x:Null}" Padding="0" HorizontalAlignment="Left" VerticalAlignment="Top">
</Button>
<Label x:Name="label1" Width="100" Height="30" Margin="10 10 0 0" BorderThickness="0" BorderBrush="{x:Null}" Padding="0" HorizontalAlignment="Left" VerticalAlignment="Top" Background="Bisque">
</Label>
</StackPanel>
</Window>
MainWindow.XAML.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace UITest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.button1.Click += Button1_Click;
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
label1.Background = Brushes.Black;
Thread.Sleep(2000);
label1.Background = Brushes.Bisque;
}
}
}
答案 0 :(得分:6)
您正在阻止UI线程。试试这个:
private async void Button1_Click(object sender, RoutedEventArgs e)
{
label1.Background = Brushes.Black;
await Task.Delay(2000);
label1.Background = Brushes.Bisque;
}