WPF:是微軟.net的3W戰略之一 (WF, WPF, WCF)
WPF主要用來做遊戲 是一個非常好的選擇
具體步驟:
1.在vs2010中建立一個C# WPF應用程式
2.App.xaml 檔案 是程式入口 可以按F5或Ctrl+F5運作程式
3.在 MainWindow.xaml(建立項目時系統自動為建立的預設視窗,可以自行添加視窗) 中 添加代碼如下:
<Canvas x:Name="Ca" Width="800" Height="600" Background="Green" MouseLeftButtonDown="Ca_MouseLeftButtonDown"></Canvas>
在界面上添加一個畫布 取名為“Ca” 設定其寬度和高度及背景色 最後還綁定了一個事件:滑鼠右鍵按下事件
4.在 MainWindow.xaml 檔案下 右鍵檢視代碼
添加如下代碼
public MainWindow() { InitializeComponent(); rect = new Rectangle(); rect.Fill = new SolidColorBrush(Colors.Blue); rect.Width = 50; rect.Height = 50; rect.RadiusX = 5; rect.RadiusY = 5; Ca.Children.Add(rect); Canvas.SetLeft(rect, 0); Canvas.SetTop(rect, 0); } Rectangle rect; private void Ca_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { //建立移動動畫 Point point = e.GetPosition(Ca); Storyboard storyboard = new Storyboard(); //建立X軸方向動畫 DoubleAnimation doubleAnimation = new DoubleAnimation(Canvas.GetLeft(rect), point.X, new Duration(TimeSpan.FromMilliseconds(500))); Storyboard.SetTarget(doubleAnimation, rect); Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Left)")); storyboard.Children.Add(doubleAnimation); //建立Y軸方向動畫 doubleAnimation = new DoubleAnimation(Canvas.GetTop(rect), point.Y, new Duration(TimeSpan.FromMilliseconds(500))); Storyboard.SetTarget(doubleAnimation, rect); Storyboard.SetTargetProperty(doubleAnimation,new PropertyPath("(Canvas.Top)")); storyboard.Children.Add(doubleAnimation); //将動畫動态加載進資源内 //if (!Resources.Contains("rectAnimation")) //{ // Resources.Add("rectAnimation", storyboard); //} //動畫播放 storyboard.Begin(); }
5 .運作 app.xaml 即可看到運作效果
這可是我的第一個WPF程式哦 加油!!!