一、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名稱空間詳解