天天看点

我的第一个WPF程序

 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程序哦  加油!!!