如果单击按钮,我有一个大约需要 5 秒才能完成的功能。如果单击按钮,我想显示某种通知以指示正在处理按钮单击,例如
<Button Click="OnButtonClick" Content="Process Input" />
<Border x:Name="NotificationBorder" Opacity="0" IsHitTestVisible="False"
Width="500" Height="100" Background="White">
<TextBlock Text="Your input is being processed" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
并在按钮上的代码隐藏中单击:
private void OnButtonClick(Object sender, RoutedEventArgs e)
{
DoubleAnimation da = new DoubleAnimation
{
From = 5,
To = 0,
Duration = TimeSpan.FromSeconds(2.5),
};
// Making border visible in hopes that it's drawn before animation kicks in
NotificationBorder.Opacity = 1;
da.Completed += (o, args) => NotificationBorder.Opacity = 0;
NotificationBorder.UpdateLayout(); //Doesn't do anything
UpdateLayout(); // Doesn't do anything
NotificationBorder.BeginAnimation(OpacityProperty, da);
// Simulate calculationheavy functioncall
Thread.Sleep(5000);
}
不知何故UpdateLayout()
渲染速度不够快,通知仅在 5 秒结束后显示Thread.Sleep
。
Dispatcher.Invoke((Action)(() => NotificationBorder.Opacity = 1), DispatcherPriority.Render);
也不会工作。
此外,我不能让Thread.Sleep
运行在单独的工作线程中——在实际应用程序中,它需要从 Dispatcher 拥有的对象中读取数据并(重新)构建 UI 的一部分。
有没有办法让它在Thread.Sleep()
被调用之前可见?