WPF學習(2)-XAML
借用網上別人的一個例子來寫體會。
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="20*" ></RowDefinition>
<RowDefinition Height="100*"></RowDefinition>
</Grid.RowDefinitions>
<DockPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >
<TextBox Background="AliceBlue"></TextBox>
</DockPanel>
<Grid Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="20*"></RowDefinition>
<RowDefinition Height="20*"></RowDefinition>
<RowDefinition Height="20*"></RowDefinition>
<RowDefinition Height="20*"></RowDefinition>
<RowDefinition Height="20*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="25*"></ColumnDefinition>
<ColumnDefinition Width="25*"></ColumnDefinition>
<ColumnDefinition Width="25*"></ColumnDefinition>
<ColumnDefinition Width="25*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Button Grid.Row="0">清除</Button>
<Button Grid.Row="0" Grid.Column="1">清除</Button>
<Button Grid.Row="0" Grid.Column="2">/</Button>
<Button Grid.Row="0" Grid.Column="3">*</Button>
<Button Grid.Row="1">7</Button>
<Button Grid.Row="1" Grid.Column="1">8</Button>
<Button Grid.Row="1" Grid.Column="2">9</Button>
<Button Grid.Row="1" Grid.Column="3">-</Button>
<Button Grid.Row="2">4</Button>
<Button Grid.Row="2" Grid.Column="1">5</Button>
<Button Grid.Row="2" Grid.Column="2">6</Button>
<Button Grid.Row="2" Grid.Column="3">+</Button>
<Button Grid.Row="3">1</Button>
<Button Grid.Row="3" Grid.Column="1">2</Button>
<Button Grid.Row="3" Grid.Column="2">3</Button>
<Button Grid.Row="3" Grid.RowSpan="2" Grid.Column="3" Background="Yellow">=</Button>
<Button Grid.Row="4" Grid.ColumnSpan="2">0</Button>
<Button Grid.Row="4" Grid.Column="2">.</Button>
</Grid>
</Grid>
</Window>
這就是一個基本的小介面,效果如下
xaml是標記語言,XML,HTML都是如此,所以就是各種各樣的標記,開始,結束,在標記放入自己想要放的內容,在標記內,定義屬性啦,事件啦,去對應前臺介面的行為樣式,當然不需要刻意背誦,用多了,就知道了,沒事多拉拉控制元件,然後按照自己對美的標準,調整樣式。
那麼既然是標記語言,那麼自己是沒辦法被計算機直接識別的,所以需要有自己的直譯器,你只要知道是有個什麼鬼東西幫你解釋的就行,比如HTML,就是瀏覽器內建的直譯器,WPF程式就是微軟的.NET幫你解釋的。
前後臺的結合,前臺使用了xaml描述了介面,那麼C#語言是如何和他配合使用的呢?畢竟,你不可能就光寫個介面。其實就是分部類,Window x:Class="WpfApplication2.MainWindow,這句話意思就是在WpfApplication2名稱空間下,有一個類叫MainWindow,然後在我們比如寫一些事件的.CS內,你可以看到,他的類名字也叫MainWindow,同時前面還有一個關鍵字partial,就表示有一個東西幫我們把這個類最後整合成一個了,具體執行規則,其實也沒有必要知道。
名稱空間,就是你的前臺頁面如果用到了某個元素或內容,直譯器怎麼知道是哪一個呢?所以需要給一個名稱空間,只不過這個名稱空間比較特別,是一串類似於網址的一個字串,你可以嘗試刪除前面的網址,就會報錯了,如下
非常明顯,就是通過名稱空間,找到了元素,根據某個規則來解釋的,如果需要調動我們自己寫的內容,那麼一樣的新增引用進來,當然最好有個別名了,不然標記寫的就太長啦,不好看。
屬性和事件,比如一個標記,button,你要改變他的樣式和行為,那麼就是定義屬性和事件啦,不同的有不同的效果,需要用的時候看文件,不需要刻意記憶,用多了,自然就記得了。
元素的巢狀,一個好的xaml樹形結構,就是要條例清晰,讓你一目瞭然,那麼在什麼標記裡面巢狀不一樣的元素,就特別重要,我覺得這個主要還是經驗的問題,更多的,可能還是美工來處理,但是咱們搞.NET,有可能壓根就沒有美工,所以慢慢培養自己的美感,非常重要。
資料繫結或依賴屬性或附加屬性,這個後面會講到,但是隻需要簡單理解為,就是屬性的一種擴充套件。