針對自定義控件的特性,由於它的界面是在一個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); }
這樣就完美解決問題了。