我正在尝试将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>
答案 0 :(得分: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);
}
}