2016-06-12 6 views
-1

私はWPFを習得しています。私はWPFアプリケーションでThreadingを使用しようとしましたが、私は何かを逃したと思います。WPFアプリケーションでThread.Sleep()が期待どおりに動作しない

私はボタンとラベルをウィンドウに配置しました。ボタンを押すと、ラベルの背景色が変わります.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; 
     } 
    } 
} 

答えて

5

あなたは、UIスレッドをブロックしています。代わりにこれを試してください:

private async void Button1_Click(object sender, RoutedEventArgs e) 
    { 
     label1.Background = Brushes.Black; 
     await Task.Delay(2000); 
     label1.Background = Brushes.Bisque; 
    } 
関連する問題