无法设置图像Opactity属性

时间:2018-04-24 10:16:06

标签: c# wpf animation

我有这张图片:

<Image x:Name="imgOsuLogo" Stretch="Uniform" Margin="205" Source="{Binding Logo}">

这个代码背后是动画图像:

public MainWindow()
    {
        InitializeComponent();
        imgOsuLogo.DataContext = workingResources;
        imgOsuLogo.Opacity = 0;
        txbUpdate.DataContext = workingResources;

        GetSongName();
        GetSkinInfo();

        Task task = new Task(() => 
        {

            Thread.Sleep(3000);
            Dispatcher.Invoke(FadeInBlackBackGround);

        });
        Task task2 = new Task(() =>
        {
            Thread.Sleep(6000);
            Dispatcher.Invoke(MainOsu);
        });
        task.Start();
        task2.Start();
    }

    private void MainOsu()
    {

        BlackCurtain.Visibility = Visibility.Collapsed;
        imgOsuLogo.Opacity = 1;
    }

    private void FadeInBlackBackGround()
    {  
        DoubleAnimation animation = new DoubleAnimation(0, 1, TimeSpan.FromSeconds(1));
        BlackCurtain.BeginAnimation(OpacityProperty, animation);
        DoubleAnimation animationLogo = new DoubleAnimation(1, 0, TimeSpan.FromSeconds(1));
        imgOsuLogo.BeginAnimation(OpacityProperty, animationLogo);
    }

imgOsuLogo.Opacity = 1;方法中的行MainOsu执行时,不透明度属性不会更改为1,即使我尝试在Visual Studio调试器中更改它。

2 个答案:

答案 0 :(得分:2)

有效动画的效果值高于本地值value precedence。要解决此问题,您必须手动更改动画的FillBehavior或取消/覆盖动画,例如:

imgOsuLogo.BeginAnimation(OpacityProperty, null);

来自MSDN:

  

动态动画或具有保留行为的动画   为了产生任何实际效果,属性的动画必须能够优先于基础(非动画)值,即使该值是在本地设置的。

答案 1 :(得分:2)

如果我正确理解了这个问题,你想在3秒后启动两个动画,并在6秒后使BlackCurtain消失,并将Image的不透明度设置回1。

这应该在没有任何任务或计时器的情况下完成所有事情:

BlackCurtain.Opacity = 0;
var a1 = new DoubleAnimation
{
    From = 0,
    To = 3,
    Duration = TimeSpan.FromSeconds(3),
    BeginTime = TimeSpan.FromSeconds(3),
    FillBehavior = FillBehavior.Stop
};
a1.Completed += (s, e) => BlackCurtain.Visibility = Visibility.Collapsed;
BlackCurtain.BeginAnimation(OpacityProperty, a1);

var a2 = new DoubleAnimation
{
    From = 1,
    To = -2,
    Duration = TimeSpan.FromSeconds(3),
    BeginTime = TimeSpan.FromSeconds(3),
    FillBehavior = FillBehavior.Stop
};
a1.Completed += (s, e) => imgOsuLogo.Opacity = 1;
imgOsuLogo.BeginAnimation(OpacityProperty, a2);