Tow*_*wer 6 .net wpf animation xaml
如何在WPF中将元素的宽度从0设置为实际宽度?
我试过这个:
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Duration="0:0:0.3" To="{Binding ElementName=MyElement, Path=ActualWidth}" From="0" Storyboard.TargetProperty="Width" Storyboard.TargetName="MyElement" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</ControlTemplate.Triggers>
Run Code Online (Sandbox Code Playgroud)
如果我将绑定更改为硬编码值,100那么宽度是适当的动画,除了我想绑定到元素的实际宽度.
如果它很重要,MyElement是一个边框,我正在制作一个标签项目的动画.
为了记录,这也不起作用:
To="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}}, Path=ActualWidth}"
Run Code Online (Sandbox Code Playgroud)
And*_*ndy 10
由于很多原因,我确定这是错误的,请随时告诉我有多少违反WPF的法律但是......我通过创建自己的BindableDoubleAnimation解决了同样的问题.
public class BindableDoubleAnimation : DoubleAnimationBase
{
DoubleAnimation internalAnimation;
public DoubleAnimation InternalAnimation { get { return internalAnimation; } }
public double To
{
get { return (double)GetValue(ToProperty); }
set { SetValue(ToProperty, value); }
}
/// <summary>
/// Dependency backing property for the <see cref="To"/> property.
/// </summary>
public static readonly DependencyProperty ToProperty =
DependencyProperty.Register("To", typeof(double), typeof(BindableDoubleAnimation), new UIPropertyMetadata(0d, new PropertyChangedCallback((s, e) =>
{
BindableDoubleAnimation sender = (BindableDoubleAnimation)s;
sender.internalAnimation.To = (double)e.NewValue;
})));
public double From
{
get { return (double)GetValue(FromProperty); }
set { SetValue(FromProperty, value); }
}
/// <summary>
/// Dependency backing property for the <see cref="From"/> property.
/// </summary>
public static readonly DependencyProperty FromProperty =
DependencyProperty.Register("From", typeof(double), typeof(BindableDoubleAnimation), new UIPropertyMetadata(0d, new PropertyChangedCallback((s, e) =>
{
BindableDoubleAnimation sender = (BindableDoubleAnimation)s;
sender.internalAnimation.From = (double)e.NewValue;
})));
public BindableDoubleAnimation()
{
internalAnimation = new DoubleAnimation();
}
protected override double GetCurrentValueCore(double defaultOriginValue, double defaultDestinationValue, AnimationClock animationClock)
{
return internalAnimation.GetCurrentValue(defaultOriginValue, defaultDestinationValue, animationClock);
}
protected override Freezable CreateInstanceCore()
{
return internalAnimation.Clone();;
}
}
Run Code Online (Sandbox Code Playgroud)
我现在可以自由地为To From属性使用绑定.
<local:BindableDoubleAnimation Storyboard.TargetProperty="Width" From="0" To="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType=Window}}"/>
Run Code Online (Sandbox Code Playgroud)