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

你可能感兴趣的:(自定义控件)