簡體   English   中英

情節提要不會為自定義FrameworkElement屬性設置動畫

[英]Storyboard doesn't animate custom FrameworkElement property

我有派生自FrameworkElement ,並且我希望WPF通過使用DoubleAnimation更新其Location屬性。 我將屬性注冊為DependendencyProperty

public class TimeCursor : FrameworkElement
{
    public static readonly DependencyProperty LocationProperty;

    public double Location
    {
        get { return (double)GetValue(LocationProperty); }
        set
        {
            SetValue(LocationProperty, value);
        }
    }

    static TimeCursor()
    {
        LocationProperty = DependencyProperty.Register("Location", typeof(double), typeof(TimeCursor));
    }
}

以下代碼設置了情節提要。

TimeCursor timeCursor;
private void SetCursorAnimation()
{
    timeCursor = new TimeCursor();
    NameScope.SetNameScope(this, new NameScope());
    RegisterName("TimeCursor", timeCursor);

    storyboard.Children.Clear();

    DoubleAnimation animation = new DoubleAnimation(LeftOffset, LeftOffset + (VerticalLineCount - 1) * HorizontalGap + VerticalLineThickness, 
                new Duration(TimeSpan.FromMilliseconds(musicDuration)), FillBehavior.HoldEnd);

    Storyboard.SetTargetName(animation, "TimeCursor");
    Storyboard.SetTargetProperty(animation, new PropertyPath(TimeCursor.LocationProperty));

    storyboard.Children.Add(animation);
}

然后,從包含上述SetCursorAnimation()方法的對象的另一種方法調用storyboard.Begin(this) ,並且此對象是從Canvas派生的。 但是, Location屬性永遠不會更新(永遠不會調用Location的set訪問器),並且不會引發任何異常。 我究竟做錯了什么?

當對依賴項屬性進行動畫處理(或在XAML中設置,或由樣式設置器設置等)時,WPF不會調用CLR包裝器,而是直接訪問基礎DependencyObject和DependencyProperty對象。 有關定義依賴項屬性以及自定義依賴項屬性的含義,請參見清單中 的“實現包裝程序”部分。

為了獲得有關屬性更改的通知,您必須注冊一個PropertyChangedCallback

public class TimeCursor : FrameworkElement
{
    public static readonly DependencyProperty LocationProperty =
        DependencyProperty.Register(
            "Location", typeof(double), typeof(TimeCursor),
            new FrameworkPropertyMetadata(LocationPropertyChanged)); // register callback here

    public double Location
    {
        get { return (double)GetValue(LocationProperty); }
        set { SetValue(LocationProperty, value); }
    }

    private static void LocationPropertyChanged(
        DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        var timeCursor = obj as TimeCursor;

        // handle Location property changes here
        ...
    }
}

還要注意,動畫依賴項屬性不一定需要情節提要。 您可以在TimeCursor實例上簡單地調用BeginAnimation方法:

var animation = new DoubleAnimation(LeftOffset,
    LeftOffset + (VerticalLineCount - 1) * HorizontalGap + VerticalLineThickness, 
    new Duration(TimeSpan.FromMilliseconds(musicDuration)),
    FillBehavior.HoldEnd);

timeCursor.BeginAnimation(TimeCursor.LocationProperty, animation);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM