WPF 自定義控件依賴屬性改變觸發故事版,動畫


針對自定義控件的特性,由於它的界面是在一個Themes/Generic.xaml文件中,並且在ControlTemplate中,所以,不能根據x:Name來訪問其中的控件,在ControlTemplate中的資源和控件(建議把資源和控件,動畫等都寫到ControlTemplate中)的訪問要通過重寫OnApplyTemplate,方法GetTemplateChild來獲得。

那么,許多特性就不能在xaml中編寫了,包括綁定。

自定義控件,依賴屬性如何綁定到Generic.xaml中的控件上,只能通過GetTemplateChild方法獲取到該控件,然后在后台綁定。動畫可以寫到資源中,到時候獲取然后Begin即可,但是不建議這么做,因為考慮到靈活性,動畫的值如果跟業務相關那就不好控制了,所以建議在后台創建動畫,雖然代碼比較多,但是靈活。

在創建依賴屬性時

public static DependencyProperty Register(
    string name,
    Type propertyType,
    Type ownerType,
    PropertyMetadata defaultMetadata
)

注意到第四個參數PropertyMetadata,該參數不僅能賦給一個默認值,還能夠添加一個函數,該函數將在依賴屬性值改變的時候執行,我們的動畫Begin就在這里面,但是該方法是靜態的又該怎么弄?

請看代碼

public float CurrentValue
        {
            get { return (float)GetValue(CurrentValueProperty); }
            set { SetValue(CurrentValueProperty, value); }
        }

        // Using a DependencyProperty as the backing store for CurrentValue.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CurrentValueProperty =
            DependencyProperty.Register("CurrentValue", typeof(float), typeof(Temp), new PropertyMetadata(50f, CurrentValueChange));

        public static void CurrentValueChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            (d as Temp).StoryboardPlay(e);
        }

        protected void StoryboardPlay(DependencyPropertyChangedEventArgs e)
        {
            Storyboard sb = new Storyboard();
            DoubleAnimation da = new DoubleAnimation();
            da.To = double.Parse(e.NewValue.ToString());
            da.Duration = new Duration(TimeSpan.Parse("0:0:1"));
            rect.BeginAnimation(Rectangle.HeightProperty, da);
        }

這樣就完美解決問題了。

源碼在這http://files.cnblogs.com/HelloMyWorld/%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8E%A7%E4%BB%B6%E5%BC%80%E5%8F%91Sample.zip


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM