Search code examples
wpfxamltriggersfadeinfadeout

Trigger a fade out animation when slider's value changes


I'm trying to bind the Opacity property of a Rectangle shape to the Slider's value. So that when its value passes 2, the Rectangle fades out and when we decrease the slider's value and it passes the value of 2 it appears again with a fade in animation. What's the best practice to do this?

<Window x:Class="Layout.AnimateOpacity"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="AnimateOpacity" Height="300" Width="300">
    <DockPanel VerticalAlignment="Center" HorizontalAlignment="Center"
               Height="300" Width="300">
        <Canvas DockPanel.Dock="Top"
                Width="300" Height="200"
                Background="Black">
            <Rectangle x:Name="myRectangle" 
                       Width="100" Height="100"
                       Canvas.Left="100" Canvas.Top="60"
                       Fill="Yellow">
            </Rectangle>
        </Canvas>
        <Slider x:Name="mySlider" DockPanel.Dock="Bottom" 
                Height="30" Width="250" 
                Value="1" Maximum="3" Minimum="0" />
    </DockPanel>
</Window>

Solution

  • Hook ValueChanged event of slider and there you can do animation based on new and old value of slider.

    XAML:

    <Slider x:Name="mySlider" DockPanel.Dock="Bottom" 
            Height="30" Width="250" 
            Value="1" Maximum="3" Minimum="0"
            ValueChanged="mySlider_ValueChanged" />
    

    Code behind:

    private void mySlider_ValueChanged(object sender,
                                       RoutedPropertyChangedEventArgs<double> e)
    {
       if (e.NewValue > 2 && e.OldValue <= 2)
       {
          DoubleAnimation fadeOutAnimation = new DoubleAnimation(0.0,
                                         new Duration(TimeSpan.FromSeconds(1)));
          myRectangle.BeginAnimation(Rectangle.OpacityProperty, fadeOutAnimation);
       }
       else if(e.NewValue < 2 && e.OldValue >= 2)
       {
          DoubleAnimation fadeInAnimation = new DoubleAnimation(1.0,
                                         new Duration(TimeSpan.FromSeconds(1)));
          myRectangle.BeginAnimation(Rectangle.OpacityProperty, fadeInAnimation);
       }
    }