用后台代码创建Storyboard

本文介绍如何使用C#代码结合XAML动态创建Storyboard动画,并将其应用于UI元素上,实现元素位置变化等效果。同时提醒开发者注意Storyboard的属性完整性,避免运行时错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

            string storyboardName = "MyStoryBoard";
            
string myXamlElement = "MyXamlElement";
            
int newLeftPosition = 120;
            Storyboard sb 
= XamlReader.Load(String.Format(
            
@"<Storyboard xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"" x:Name=""{0}"">
                <DoubleAnimation Storyboard.TargetName=""{1}""
                Storyboard.TargetProperty=""(Canvas.Left)""
                To=""{2}"" Duration=""00:00:00.1200000""/>
                </Storyboard>
", storyboardName, myXamlElement, newLeftPosition)) as Storyboard;
            
//Add a delegate to remove the storyboard from resources as soon as it is finished. 
            sb.Completed += new EventHandler(sb_Completed);
            
//Add to the resources of the page 
            this.Resources.Add(sb);
            
//Begin the storyboard which will animate the element to the correct position. 
            sb.Begin();

在不少的应用中需要动态的创建动画作出一些复杂的效果。比如说当当拖拽元素是可以简单的用c#代码创建一个storyboard并在这个board中创建一个DoubleAnimation。但是用c#代码创建动画会导致runtime errors因为这还是silverlight的一个bug。但是用 xaml 并load他成为一个简单的storyboard。
xamlReader 对象有一个非常有用的Load()方法。
这里要提醒一点  创建Storyboard一定要把属性些完整了。 不要漏写了类似x:Name这样的属性。 若够漏写silverlight不会报任何错误。在调试时是直接跳出。
我就犯了这样的错误 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值