Change animation duration with slider by binding

2019-07-23 08:46发布

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

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.

1条回答
不美不萌又怎样
2楼-- · 2019-07-23 08:49

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.

Take a look to this simple example:

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

Where the convert's code is:

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.

查看更多
登录 后发表回答