【问题标题】:Trigger a fade out animation when slider's value changes当滑块的值改变时触发淡出动画
【发布时间】:2014-02-13 02:26:50
【问题描述】:

我正在尝试将 Rectangle 形状的 Opacity 属性绑定到 Slider 的值。因此,当它的值超过 2 时,矩形 淡出,当我们减小滑块的值并且它超过 2 的值时,它会再次出现,并带有 动画淡入。这样做的最佳做法是什么?

<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>

【问题讨论】:

    标签: wpf xaml triggers fadein fadeout


    【解决方案1】:

    挂钩ValueChanged滑块事件,你可以根据滑块的新旧值做动画。

    XAML:

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

    背后的代码:

    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);
       }
    }
    

    【讨论】:

    • 非常感谢。您提供的代码运行良好,可以使用 xaml 中的触发器来完成吗?
    • 是的,但它可能会更复杂。您必须创建converter,它将根据两个 if 条件返回 True、false,并且基于这两个值,您可以使用 Trigger on DockPanel 使用 StoryBoard 切换不透明度。
    • 是的,我担心我不得不使用转换器 :( 我希望可能有一个简单的方法 :p,不过后面的代码可以完成这项工作。
    猜你喜欢
    • 1970-01-01
    • 2011-09-19
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 2012-05-15
    • 2012-09-07
    • 2011-05-06
    • 2011-06-30
    相关资源
    最近更新 更多