wpf动画——new PropertyPath属性链

在wpf中我们常用storyboard故事板装载很多的动画处理Animation,我们需要用Storyboard.SetTarget设置操作的对象,需要用Storyboard.SetTargetProperty设置操作对象的操作属性PropertyPath,本例将说明一种操作属性PropertyPath的便利方法:


1.新建一个wpf应用程序,简单修改一下xaml展示如下:

<Window x:Class="WpfApplication48.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    </Grid>
</Window>

2.后台cs修改如下(效果:点击button,button的横坐标x由12到300,播放过程动画):

    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.button1.RenderTransform = new TranslateTransform();

            Storyboard sb = new Storyboard();
            DoubleAnimation da = new DoubleAnimation();
            da.From = 12;
            da.To = 300;
            da.Duration = TimeSpan.FromSeconds(3);
            sb.Children.Add(da);

            DependencyProperty[] propertyChain = new DependencyProperty[]
            {
                Button.RenderTransformProperty,
                TranslateTransform.XProperty
            };

            Storyboard.SetTarget(da, this.button1);
            Storyboard.SetTargetProperty(da, new PropertyPath("(0).(1)", propertyChain));

            sb.Completed += new EventHandler((object sender1, EventArgs e1) => { MessageBox.Show("completed"); });
            sb.Begin();
        }
    }

一般我们在写到Storyboard.SetTargetProperty时遇到new PropertyPath,

如果是简单的属性,例如Button.WidthProperty,我们可以直接new PropertyPath(Button.WidthProperty)达到目的,
但如果你发现你需要操作到的属性无法在Button中直接'.'出来,就需要用到上例用到的属性链方法:

首先定义一个属性链:

            DependencyProperty[] propertyChain = new DependencyProperty[]
            {
                Button.RenderTransformProperty,
                TranslateTransform.XProperty
            };

属性链的写法,定义一个DependencyProperty属性的数组,该数组中的元素均是Property属性,且按照从属关系先后排列,例如上例中,我们需要先将button的RenderTransform设置为TranslateTransform,然后通过TranslateTransform的XProperty来更改button的x坐标,

当然,别忘了初始化button的RenderTransform属性= new TranslateTransform(),否则动画将没有效果。

posted on 2012-09-14 16:45  影天  阅读(3795)  评论(1编辑  收藏  举报

导航