MegaMind MegaMind - 1 year ago 102
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.

<Window.Resources>
<Style x:Key="somestyle" TargetType="Button">
<Style.Triggers>
<DataTrigger Binding="{Binding IsControlVisible,UpdateSourceTrigger=PropertyChanged}" Value="False">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Duration="0:0:1.5" Storyboard.TargetProperty="Opacity" To="0" />
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Duration="0:0:1.5" Storyboard.TargetProperty="Opacity" To="1" />
</Storyboard>
</BeginStoryboard>
</DataTrigger.ExitActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<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}"/>
</StackPanel>

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}" />
    (...)
</Style>

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