【问题标题】:Changing opacity from code-behind从代码隐藏更改不透明度
【发布时间】:2013-12-14 15:21:07
【问题描述】:

为什么窗口代码隐藏中的以下事件无效?

void about_Click(object sender, RoutedEventArgs e)
{
   // TopLevel.Opacity = 1.0, Splashscreen.Opacity = 0.0
   TopLevel.Opacity = 0.1;
   // still: TopLevel.Opacity = 1.0
   Splashscreen.Opacity = 1.0;
   // still: Splashscreen.Opacity = 0.0
}

不透明度值不会改变。

我发现以下触发器是我的问题的原因:

<Window.Triggers>
    <EventTrigger RoutedEvent="FrameworkElement.Loaded">
        <BeginStoryboard Storyboard="{StaticResource splashscreenanimation}" />
    </EventTrigger>
</Window.Triggers>

当我删除它时,代码隐藏正在工作。

为了完整起见,这是动画:

<Window.Resources>
    <Storyboard x:Key="splashscreenanimation">
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)"
                                        Storyboard.TargetName="Splashscreen"
                                        BeginTime="0:0:0.900">
            <EasingDoubleKeyFrame KeyTime="0:0:1.5"
                                    Value="0" />
        </DoubleAnimationUsingKeyFrames>
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)"
                                        Storyboard.TargetName="TopLevel"
                                        BeginTime="0:0:0.900">
            <EasingDoubleKeyFrame KeyTime="0:0:1.5"
                                    Value="1" />
        </DoubleAnimationUsingKeyFrames>
    </Storyboard>
</Window.Resources>

Solution:在后面的代码中,您可以通过首先执行来删除动画:Splashscreen.BeginAnimation(UserControl.OpacityProperty, null);
(启动画面是一个用户控件)。
我还尝试将FillBehavior="HoldEnd"FillBehavior="Stop" 添加到情节提要中,但没有让它正常工作。

【问题讨论】:

  • 我不同意你的最后评论......这对我来说很好。也许您可以展示一个仍然表现出这种行为的 XAML 的简化版本?

标签: wpf animation opacity


【解决方案1】:

再次出现依赖属性值优先级的相同问题。

看看优先级。

  1. 属性系统强制。

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

  3. 本地值。可以通过“包装器”属性的便利设置本地值,这也等同于在 XAML 中设置为属性或属性元素,或者通过使用特定实例的属性调用 SetValue API。

在你的情况下,动画接管了。

您的代码是#3。您正在设置本地值,但动画仍会接管。

void about_Click(object sender, RoutedEventArgs e)
{
   // TopLevel.Opacity = 1.0, Splashscreen.Opacity = 0.0
   TopLevel.Opacity = 0.1;
   // still: TopLevel.Opacity = 1.0
   Splashscreen.Opacity = 1.0;
   // still: Splashscreen.Opacity = 0.0
}

我希望您现在终于了解优先级的工作原理。 :) :) :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-19
    • 2012-02-27
    • 1970-01-01
    • 2012-09-20
    • 2012-11-14
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    相关资源
    最近更新 更多