Silverlight 中厚度动画 (Margin, Padding, BorderThickness)






4.33/5 (10投票s)
如何在 Silverlight 中轻松地动画化厚度 (Margin, Padding, BorderThickness)。
引言
在 Silverlight 中,没有像 WPF 中那样可以使用的 ThicknessAnimation
。因此,像我一样,许多开发人员希望能够动画化 Border
的 Margin
、Padding
或 BorderThickness
。
好消息!我有一个基于 包装器模式的简洁解决方案。
它是如何工作的?
所有操作都通过 ThicknessWrapper
类完成
PropertyName
是要动画化的属性名称。Side
是要动画化的边;由于Side
是一个标志枚举,您可以指定多个值。Target
是要动画化的目标对象。Value
是要动画化的Thickness
边的尺寸。
代码并不复杂;每次这些属性中的一个发生变化时,我都会更新 Target
的边距。
private void UpdateMargin()
{
if(Target != null)
{
var thicknessProperty = Target.GetType().GetProperty(PropertyName);
var currentThickness = (Thickness)thicknessProperty.GetValue(Target, null);
var nextThickness = new Thickness(
CalculateThickness(Side.Left, currentThickness.Left),
CalculateThickness(Side.Top, currentThickness.Top),
CalculateThickness(Side.Right, currentThickness.Right),
CalculateThickness(Side.Bottom, currentThickness.Bottom)
);
thicknessProperty.SetValue(Target, nextThickness, null);
}
}
private double CalculateThickness(ThicknessAnimation.Side sideToCalculate,
double currentValue)
{
return (Side & sideToCalculate) == sideToCalculate ? Value : currentValue;
}
现在您只需要在 XAML 代码中使用包装器并对其进行动画化即可。例如,我对边框的 BorderThickness
和 Margin
播放了动画。
<Grid x:Name="LayoutRoot" Background="White">
<Grid.Resources>
<Storyboard x:Key="animation">
<DoubleAnimation Storyboard.TargetName="rectTopMargin"
Storyboard.TargetProperty="Value" From="0"
To="100" Duration="00:00:1"></DoubleAnimation>
<DoubleAnimation Storyboard.TargetName="rectStrokeThickness"
Storyboard.TargetProperty="Value" From="0"
To="20" Duration="00:00:1"></DoubleAnimation>
</Storyboard>
</Grid.Resources>
<local:ThicknessWrapper x:Name="rectTopMargin"
Target="{Binding ElementName=rect}" Side="Top"
PropertyName="Margin"></local:ThicknessWrapper>
<local:ThicknessWrapper x:Name="rectStrokeThickness"
Target="{Binding ElementName=rect}" Side="Left, Right"
PropertyName="BorderThickness"></local:ThicknessWrapper>
<StackPanel>
<Button Content="Click to animate" Click="Button_Click"></Button>
<Border x:Name="rect" HorizontalAlignment="Left"
BorderBrush="Black" VerticalAlignment="Top"
Background="Green" Height="50" Width="50"></Border>
</StackPanel>
</Grid>
结论
我还没有找到更简单的解决方案!:)