通过绑定使用滑块更改动画持续时间 [英] Change animation duration with slider by binding
问题描述
我正在使用故事板中的以下代码旋转 3D 房屋:
I am spinning a 3D house with the following code inside a storyboard:
<DoubleAnimation Storyboard.TargetName="HouseRotate" Storyboard.TargetProperty="Angle" From="0" To="-359" Duration="{Binding StringFormat=0:0:{0}, ElementName=slDuration, Path=Value, UpdateSourceTrigger=PropertyChanged}" RepeatBehavior="Forever"/>
我希望持续时间属性根据滑块值进行更改,但它似乎停留在 1 秒.我知道滑块的值正在正确更改,因为我已将其输出到标签.
I want the duration property to change based on the slider value, but it seems to be stuck at 1 second. I know the value of the slider is changing properly, because I have outputted it to a label.
推荐答案
在我看来你需要一个合适的转换器才能从 double
(Slider
的属性值返回 double
) 到 持续时间 结构.
In my opinion you need a proper converter in order to convert from double
(Slider
's property Value returns a double
) to a Duration struct.
看看这个简单的例子:
<Window.Resources>
<local:DoubleToDurationConverter x:Key="DoubleToDurationConverter" />
</Window.Resources>
<StackPanel>
<Button Content="Click me for an animation" Margin="20" Padding="20">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard>
<ColorAnimation To="Green"
Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)"
FillBehavior="Stop"
Duration="{Binding ElementName=slider, Path=Value, Mode=OneWay, Converter={StaticResource DoubleToDurationConverter}}" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
<Slider Name="slider" Minimum="10" Maximum="40" Value="30"
Margin="5" AutoToolTipPlacement="TopLeft" IsSnapToTickEnabled="True" />
</StackPanel>
转换代码在哪里:
public class DoubleToDurationConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Duration duration = new Duration(TimeSpan.FromSeconds((double)value));
return duration;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
请注意,在运行时无法更改动画的持续时间.您可以在空闲时更改它.
Keep in consideration that it is not possible to change the animation's duration while it is running. You can change it just when it is idle.
这篇关于通过绑定使用滑块更改动画持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!