WPF第一个程序和XAML初探

 一、WPF中为什么要用XAML?

        XAML的优点,可以参考下面的文章:http://www.cnblogs.com/free722/archive/2011/11/06/2238073.html,具体的体现还会在以后的章节中说明。

二、第一个WPF程序

2.1新建->项目->WPF应用程序:如图1

      

图1

 

图2

2.2在工具栏拖一个按钮Button,如图2所示,双击,后台代码如下

public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

        }

         private void button1_Click(object sender, RoutedEventArgs e)

        {

            MessageBox.Show("Hello WPF!");

        }

    }

 

2.3最后按F5,ok,一个Hello WPF就出现了

三、剖析最简单的XMAL代码

3.1新建一个窗口

  对应的XAML代码为下面的代码:

<Window x:Class="Chap_01_XAML.Window1"   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="Window1" Height="300" Width="300">

    <Grid>

    </Grid>

</Window>

3.2剖析Attribute和Property

  如果要剖析上述代码的话,要从Attribute和Property说起,接触过web的话知道Attitubute是DOM的特征,在这里差不多,Attribute是xaml的特征,Property是从面向对象的角度的属性,是属于一个对象的的属性。其实还是有些联系的,那就是一个C#后台的对象的属性Property和XAML的Attribute是有映射关系的,不过一般情况下,是多个Attribute对应一个Property。

3.3正题

  现在进入正题,上面的代码可以简化成:

<Window>

    <Grid>

    </Grid>

</Window>

 

  在这里Grid是Windows的一个属性,attribute和Property一对一的映射。接下来看一下xmlns

  x:Class="Chap_01_XAML.Window1"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml

  其中xmlns为xaml文件的命名空间,http://schemas.microsoft.com/winfx/2006/xaml/presentation对应了.NET里多个命名空间:

. System.Windows
. System.Windows.Automation
. System.Windows.Controls
. System.Windows.Controls.Primitives
. System.Windows.Data
. System.Windows.Documents
. System.Windows.Forms.Integration
. System.Windows.Ink
. System.Windows.Input
. System.Windows.Media
. System.Windows.Media.Animation
. System.Windows.Media.Effects
. System.Windows.Media.Imaging
. System.Windows.Media.Media3D
. System.Windows.Media.TextFormatting
. System.Windows.Navigation
. System.Windows.Shapes

       http://schemas.microsoft.com/winfx/2006/xaml对应了一些与XAML的语法和编译相关的CLR名称空间。由于“xmlns:x”的缘故,如果使用这些命名空间里面的类型的话要加上x:当然x可以是其他的字母或单词(通常是不改名的,后面的章节会讲到x),为什么上面一个的没有加呢,那是因为,每个xaml文件里面都允许一个默认的命名空间,这个命名空间经常调用,如果不经常调用的话,我们去默认,那我们经常调用的话就要加“别名”,自己就给自己带来了麻烦,所以我们把经常最经常用的默认,其实我们保存默认状态就好了。

3.4后台代码中的对象和前台对象怎么映射

       主要是通过http://schemas.microsoft.com/winfx/2006/xaml和后台代码的partial关键词。partial使同一个类可以多出定义,最终相同名字的类通过编译合并成一个类。我们可以通过反vs下面的这个工具(如图3所示)查看bin目录下生成的.exe文件(不是这个.vshost.exe),如图4所示:

图3

图4

 

发现了只有一个window1这个类,如果在.cs文件里面在加一个下面的代码(即使说这段代码没有什么用处,这里只是用来说明partial的作用),生成的文件里面会有如图5的一个变量,

去掉下面的代码的如图6,发现没有了btn这个变量。

    public partial class Window1 : Window

    {

        private Button btn;

    }

 

图5

 

  图6

四、总结

  本文主要粗略的说明了一下WPF和XAML,让我对WPF和XAML有了初步的认识,如果有不足的地方,请大牛们指点。下一篇:x名称空间详解

posted @ 2012-09-01 21:34  haiziguo  阅读(9164)  评论(3编辑  收藏  举报