2014-02-12 196 views
1

我试图将不透明度属性的矩形形状绑定到滑块的值。因此,当它的值通过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> 

回答

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

太谢谢你了。你提供的代码工作得很好,可以使用xaml中的触发器来完成吗? – Vahid

+1

是的,它可以是更复杂的。你必须创建'converter',它将根据两个条件返回True和false,并基于这两个值,你可以使用'Trigger on DockPanel'来使用'StoryBoard'切换不透明度。 –

+0

是的,我害怕我不得不使用转换器:(我希望可能有一个简单的方法:p,后面的代码将完成这项工作。 – Vahid

相关问题