我想显示一些文字和图片以某种方式显示文字2秒,然后图片将替换它。 也是在那个时候不要让UI卡住。
我尝试了以下内容: 在WPF UI中:
<Border x:Name="ComparisonResultImageBox" Visibility="Visible" Grid.Row="2" Grid.Column="2" Background="White" Margin="8,5,8,5">
<Image x:Name="DiffrenceImage"></Image>
</Border>
和
<Border x:Name="LoadingComparisonResultLabel" Visibility="Collapsed" Grid.Row="2" Grid.Column="2" Background="White" Margin="0,5,8,5">
<Label Content="Loading Comparison Result..." FontFamily="Open Sans" FontSize="13" ></Label>
</Border>
然后在代码中,当点击页面上的某个按钮时,我调用了以下方法:
private void ClearComparePicture() {
DiffrenceImage.Source = null;
LoadingComparisonResultLabel.Visibility = Visibility.Visible;
ComparisonResultImageBox.Visibility = Visibility.Collapsed;
Thread.Sleep(2000);
DiffrenceImage.Source = newBitmapImage;
LoadingComparisonResultLabel.Visibility = Visibility.Collapsed;
ComparisonResultImageBox.Visibility = Visibility.Visible;
}
问题是文本在睡眠时间内没有显示....
答案 0 :(得分:3)
您不应该在UI线程上使用任何阻塞调用(长时间运行同步)。
可能使这项工作最简单的变化是使用async Task
或async void
。
private async Task ClearComparePicture() {
DiffrenceImage.Source = null;
LoadingComparisonResultLabel.Visibility = Visibility.Visible;
ComparisonResultImageBox.Visibility = Visibility.Collapsed;
await Task.Delay(2000);
DiffrenceImage.Source = newBitmapImage;
LoadingComparisonResultLabel.Visibility = Visibility.Collapsed;
ComparisonResultImageBox.Visibility = Visibility.Visible;
}