为什么 Window 代码隐藏中的以下事件没有效果?
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);
(Splashscreen 是一个 UserControl)。
我还尝试将 FillBehavior="HoldEnd"
或 FillBehavior="Stop"
添加到 Storyboard,但没有让它正常工作。
最佳答案
你又一次遇到了与依赖属性值优先级相同的问题。
查看优先级。
属性(property)制度强制。
事件动画,或具有保持行为的动画。为了产生任何实际效果,属性的动画必须能够优先于基本(非动画)值,即使该值是在本地设置的。
本地值。可以通过方便的“包装器”属性设置本地值,这也等同于设置为 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
}
我希望现在您终于了解优先级的工作原理。 :) :) :)
关于wpf - 从代码隐藏更改不透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20268639/