更改不透明度时窗口未重绘

时间:2012-05-25 09:25:45

标签: c# wpf xaml

我一直在尝试创建一个通知窗口,但我正在努力弄清楚为什么在运行它时不会发生这种不透明度的转变。相反,窗口将保持一秒钟然后关闭而没有任何可见的变化。通过其他方法进行的所有其他尝试也都失败了,所以它必须是我缺少的一些属性。谢谢你的帮助!

    public void RunForm(string error, MessageBoxIcon icon, int duration)
    {
        lblMessage.Text = error;
        Icon i = ToSystemIcon(icon);
        if (i != null)
        {
            BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(i.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            imgIcon.Source = bs;
        }
        this.WindowStartupLocation = WindowStartupLocation.Manual;
        this.Show();
        this.Left = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Right - this.RestoreBounds.Width - 20;
        this.Top = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Bottom - this.RestoreBounds.Height - 20;
        while (this.Opacity > 0)
        {
            this.Opacity -= 0.05;
            Thread.Sleep(50);
        }
        this.Close();
    }


<Window Width="225" Height="140" VerticalContentAlignment="Center" HorizontalAlignment="Center" ShowActivated="True" ShowInTaskbar="False"
ResizeMode="NoResize" Grid.IsSharedSizeScope="False" SizeToContent="Height" WindowStyle="None" BorderBrush="Gray" 
BorderThickness="1.5" Background="White" Topmost="True" AllowsTransparency="True" Opacity="1">
<Grid Height="Auto" Name="grdNotificationBox" >
    <Image Margin="12,12,0,0" Name="imgIcon" Stretch="Fill" HorizontalAlignment="Left" Width="32" Height="29" VerticalAlignment="Top" />
    <TextBlock Name="lblMessage" TextWrapping="Wrap" Margin="57,11,17,11"></TextBlock>
</Grid>

2 个答案:

答案 0 :(得分:2)

这不起作用: 完整的WPF处理在一个单独的线程中完成(技术上两个但不重要)。你改变不透明度并直接让ui线程睡眠,再次更改它并将其发送回睡眠状态。 ui线程从来没有时间处理你所做的事情。即使删除睡眠也无济于事,因为速度快,而且ui线程无法处理任何请求。了解您的代码和WPF处理是在同一个线程中完成很重要,您需要的时间越长,WPF获得的时间就越少,反之亦然。

要解决此问题,您需要使用animations。他们正是为了这些事情。结帐thread

答案 1 :(得分:1)

您基本上阻止了在while loop中更新的UI线程。使用计时器执行此操作或更恰当地使用Background Worker Thread

编辑:由于 dowhilefor 表示您可以为此目的使用WPF动画。 This article在此详细讨论。

DoubleAnimation da = new DoubleAnimation();
da.From = 1;
da.To = 0;
da.Duration = new Duration(TimeSpan.FromSeconds(2));
da.AutoReverse = true;
da.RepeatBehavior = RepeatBehavior.Forever;
rectangle1.BeginAnimation(OpacityProperty, da);
相关问题