? 前幾篇一直在Blend中工作沒體現出開發者的作用,本篇將為訂書器(Stapler)添加自定義粒子效果,當訂書器被點擊時產生更好的視覺效果。其中將使用到nerdplusart?的Silverlight Particle Generator?粒子特效工具。
在結束本章內容后,點擊Stapler 和Candies 將達到以下效果:
?
?
1. 在Projects面板中新增Interactivity?文件夾,再為Interactivity 新增ParticlesBehavior?子文件夾:
2. 右鍵ParticlesBehavior文件夾->Add New Item->Behavior,添加ParticlesBehavior:
3.?下載Silverlight Particle Generator 源代碼,將代碼中的ParticleControl.xaml?和ParticleControl.xaml.cs?文件加入(Add Existing Item)到ParticlesBehavior 文件夾:
4. 右鍵項目點擊“Edit in Visual Studio”,對PaticlesBehavior.cs進行編輯來跟蹤鼠標移動位置。將ParticlesBehavior 類聲明改為Behavior<Canvas>,通過修改后AssociatedObject 類型將成為Canvas。在OnAttached 和OnDetaching 方法中分別添加和刪除MouseMove 事件,當鼠標移動時便可記錄下當前鼠標位置:
public class ParticlesBehavior : Behavior<Canvas> {private Point currentMousePosition;public ParticlesBehavior(){this.ShowParticles = new ActionCommand(this.OnShowParticles);}protected override void OnAttached(){base.OnAttached();AssociatedObject.MouseMove += new MouseEventHandler(AssociatedObject_MouseMove);}protected override void OnDetaching(){base.OnDetaching();AssociatedObject.MouseMove -= new MouseEventHandler(AssociatedObject_MouseMove);}void AssociatedObject_MouseMove(object sender, MouseEventArgs e){currentMousePosition = e.GetPosition(null);}public ICommand ShowParticles{get;private set;}private void OnShowParticles(){ParticleControl p = new ParticleControl();p.OffsetX = currentMousePosition.X;p.OffsetY = currentMousePosition.Y;AssociatedObject.Children.Add(p);}
}
?
5. VS里編譯后回到Blend,在Assets->Behavior 中將會看到ParticlesBehavior 選項,將ParticlesBehavior 加入LayoutRoot中:
點擊Triggers右側的“+”按鈕添加新EventTrigger;點擊EventTrigger將SourceName設為staplerPath,EventName設為MouseLeftButtonDown;再次點擊“+”為可為其他物品添加ParticlesBehavior特效。另,在ParticlesBehavior.cs中增加一些代碼,便可出現下圖中Particles Properties設置窗口(詳情可下載源代碼):
6. 在Blend中F5,點擊圖片中的訂書器(Stapler)便會出現粒子效果(但其不會自動消失),再點擊Candies也會出現粒子效果,問題是所有的粒子效果仍然不能消失。打開ParticleControl.xaml.cs 進行編輯:??
??? a. 在ParticleControl 類中定義int?型totalParticlesCreated?
??? b. 將this.particles.Count?替換為totalParticlesCreated??
??? c. 在SpawnParticle方法最后添加totalParticlesCreated++?
至此粒子效果就會自動消失了。
?
7. 最后為staplerPath添加RemoveElementAction,目的是為了每個物品只能點擊一次:
將SourceName 和TargetName 都設置為staplerPath,EventName依然為MouseLeftButtonDown:
源代碼下載:
本文轉自Gnie博客園博客,原文鏈接:http://www.cnblogs.com/gnielee/archive/2010/01/02/silverlight-puzzle-game-part4.html,如需轉載請自行聯系原作者