Changing opacity from code-behind
animation, opacity, wpf
Solution
Again you and again the same issue with dependency property value precedence.
Take a look at the priorities.
Property system coercion.
Active animations, or animations with a Hold behavior. In order to have any practical effect, an animation of a property must be able to have precedence over the base (unanimated) value, even if that value was set locally.
Local value. A local value might be set through the convenience of the "wrapper" property, which also equates to setting as an attribute or property element in XAML, or by a call to the SetValue API using a property of a specific instance.
In your case animation takes over.
Your code here is #3. You are setting the local value but animation still takes over.
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
}
I hope now you finally understand how priorities work. :) :) :)
Problem
Why has the following event in a Window code-behind no effect? ``` 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 } ``` The opacity values do not change. I discovered that the following Trigger is the cause of my issue: ``` <Window.Triggers> <EventTrigger RoutedEvent="FrameworkElement.Loaded"> <BeginStoryboard Storyboard="{StaticResource splashscreenanimation}" /> </EventTrigger> </Window.Triggers> ``` When I remove it the code-behind is working. For completeness, this is the animation: ``` <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: In code behind you can remove the animation by first executing: `Splashscreen.BeginAnimation(UserControl.OpacityProperty, null);` (Splashscreen is a UserControl). I also tried adding `FillBehavior="HoldEnd"` or `FillBehavior="Stop"` to the Storyboard but did'nt get it to work properly.