Dot-Net
WPF中的動畫寬度到實際寬度?
如何將元素的寬度從 0 設置為 WPF 中的實際寬度?
我試過這個:
<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>如果我將綁定更改為硬編碼值,例如
100,則寬度會正確設置動畫,但我想綁定到元素的實際寬度。如果重要的話,
MyElement是一個邊框,我正在為一個標籤項設置動畫。為了記錄,這也不起作用:
To="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}}, Path=ActualWidth}"
我確信這是錯誤的,原因有很多,請隨時告訴我我違反了多少 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();; } }我現在可以自由地為 To From 屬性使用綁定。
<local:BindableDoubleAnimation Storyboard.TargetProperty="Width" From="0" To="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType=Window}}"/>