MegaMind MegaMind - 1 year ago 112
C# Question

WPF Data trigger causing flash while loading animation

I have a data trigger which upon set to false hide the related controls with animation. Now when the screen is being loaded values of the properties are already false, still it run the animation and fade the controls thus hide them.

It is causing a brief flash on screen.

I expect those controls to remain hidden on screen until I set the property to true.

<Style x:Key="somestyle" TargetType="Button">
<DataTrigger Binding="{Binding IsControlVisible,UpdateSourceTrigger=PropertyChanged}" Value="False">
<DoubleAnimation Duration="0:0:1.5" Storyboard.TargetProperty="Opacity" To="0" />
<DoubleAnimation Duration="0:0:1.5" Storyboard.TargetProperty="Opacity" To="1" />
<StackPanel VerticalAlignment="Center">
<Button Width="100" Height="50" Content="Toggle Visibiity" Click="Button_Click"/>
<Button Width="200" Height="50" Content="Something Something" Margin="0 20 0 0" Style="{StaticResource somestyle}"/>

Answer Source

The problem is that when your control is loaded and the style is applied, the trigger is evaluated and, since initially IsControlVisible is false, the first storyboard is started, animating the Opacity from 1 (default value) to 0. So the solution is to set the initial Opacity value to 0 (or, better yet, to a value corresponding to the initial value of IsControlVisible). To do that it is sufficient to add an appropriate setter to your style:

<Style x:Key="somestyle" TargetType="Button">
    <Setter Property="Opacity" Value="{Binding IsControlVisible, Mode=OneTime}" />

It is advisable to set the binding mode to OneTime so that when the value of IsControlVisible changes later on, the Opacity is only controlled by the animations and not the binding. Also, I didn't use any converter, but as it turns out the framework is smart enough to properly convert bool to double.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download