我們緊接着上篇,開始我們的Metro風格應用開發。
-----------------------------------我是華麗的分割線-----------------------------------------
12.在 XAML 中定義應用布局
a)在接下來的在 XAML 中定義應用布局、添加控件和內容和顯示數據 3 個部分中,
我們將學習在 XAML 中創建用戶界面的基本知識。為了學習這些基本知識,我們創建了一個簡單的單頁博客閱讀器,
以顯示單個博客信息提要的文章。如果你已經有使用 XAML 的經驗並且熟悉 XAML 布局、控件和數據綁定,
則可以跳過這些部分且不用完成練習。但不要跳過為日期轉換器添加代碼的部分,稍后在我們的應用中會用到它。
讓我們回到添加頁面和導航部分中的創建完整的 Metro 風格應用。
b)應用布局用於指定應用中每個對象的大小和位置。要定位視覺對象,你必須將其置於某個Panel控件或其他容器對象中。
XAML 布局系統提供了各種 Panel 控件,例如用作你在其中排列控件的 Grid、Canvas 和 StackPanel。
XAML 布局系統既支持絕對布局,也支持動態布局。在絕對布局中,使用顯式的 x 和 y 坐標(例如,使用 Canvas)來定位控件。
在動態布局中,當應用重新調整大小時,布局容器和控件會隨之自動改變大小和位置(例如使用StackPanel或Grid的情況)。
在實際過程中,通常通過結合使用絕對布局和動態布局的方式,以及將面板嵌入到其他面板的方式來定義應用的布局。
博客閱讀器應用的典型布局如下:頂部為標題,左側是文章列表,右側是所選文章的內容。
c)默認情況下,空白應用模板僅包含一個空白 Grid,它是我們的 UI 的根元素。為了指定我們的布局,我們將Grid划分為兩行。
首行顯示博客標題。在第二行中,我們嵌入另一個Grid,將它分為兩列,然后添加其他一些布局容器以顯示博客內容。
d)代碼如下:

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <Grid.RowDefinitions> <RowDefinition Height="140" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <!-- Title --> <TextBlock x:Name="TitleText" Text="{Binding Title}" VerticalAlignment="Center" FontSize="48" Margin="56,0,0,0"/> <!-- Content --> <Grid Grid.Row="1"> <Grid.ColumnDefinitions> <ColumnDefinition Width="2*" MinWidth="320" /> <ColumnDefinition Width="3*" /> </Grid.ColumnDefinitions> <!-- Left column --> <!-- The default value of Grid.Column is 0, so we do not need to set it to make the ListView show up in the first column. --> <ListView x:Name="ItemListView" ItemsSource="{Binding Items}" Margin="60,0,0,10" SelectionChanged="ItemListView_SelectionChanged"> <ListView.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Title}" FontSize="24" Margin="5,0,0,0" TextWrapping="Wrap" /> <TextBlock Text="{Binding Author}" FontSize="16" Margin="15,0,0,0"/> <TextBlock Text="{Binding PubDate,Converter={StaticResource dateConverter}}" FontSize="16" Margin="15,0,0,0"/> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> <!-- Right column --> <!-- We use a Grid here instead of a StackPanel so that the WebView sizes correctly. --> <Grid DataContext="{Binding ElementName=ItemListView, Path=SelectedItem}" Grid.Column="1" Margin="25,0,0,0"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <TextBlock x:Name="PostTitleText" Text="{Binding Title}" FontSize="24"/> <WebView x:Name="ContentView" Grid.Row="1" Margin="0,5,20,20"/> </Grid> </Grid> </Grid>
我們更詳細地看看此 XAML 可以做什么。若要在 Grid 中定義行,你需要在 Grid.RowDefinitions 集合中添加 RowDefinition 對象。
你可以在 RowDefinition 中設置屬性,以指定行的外觀。添加列的方法是相同的,
只不過要使用 ColumnDefinition 對象和 Grid.ColumnDefinitions 集合。第一個行定義(行 0)上的 Height="140" 屬性設置
將頂部的行設置為 140 個與設備無關的像素的絕對高度。無論行的內容或應用的大小如何變化,此高度都不會改變。
第二個行定義(行 1)上的 Height="*" 設置告訴底部行占用行 0 占用后的所有空間。這通常稱為星形比例縮放。
我們在第二個Grid的列定義中也使用了比例縮放。寬度設置Width="2*"和Width="3*"要求Grid將自身分為 5 個相等的部分。
兩個部分用於第一列,三個部分用於第二列。要在Grid中定位某個元素,你需要設置該元素的附加屬性Grid.Row和 Grid.Column。
行和列編號是從零開始的。這些屬性的默認值是 0,因此如果未設置任何內容,則該元素將位於第一行第一列。
<Grid Grid.Row="1"> 元素在根 Grid 的底部行嵌入一個 Grid。該Grid被划分為兩列。元素<ListView x:Name="ItemListView">
將一個ListView添加到底部的左側列中Grid。元素<Grid Grid.Column="1">將另一個Grid添加到底部的右側列中Grid。
我們將該Grid划分為兩行。設置Height="Auto"要求頂行盡可能地調整高度以適合其內容。底行則占用剩下的所有空間。
e)我們的 UI 中需要布局面板的最后一個部分是博客文章列表。
在該列表中,我們需要按如下所示排列標題、作者和日期。
當你需要在頁面 UI 的一個小的子部分中自動排列連續元素時,通常使用一個 StackPanel。
StackPanel是一種簡單的布局面板,可以將子元素按水平或垂直方向排列到單行中。
你可以使用StackPanel.Orientation屬性來指定子元素的方向。 Orientation屬性的默認值是 Orientation.Vertical。
我們使用StackPanel來排列博客文章列表中的項。我們看到在使用模板設置數據格式會用到它。
StackPanel 的 XAML 如下:
<StackPanel>
<TextBlock Text="{Binding Path=Title}" FontSize="24" Margin="5,0,0,0" TextWrapping="Wrap" />
<TextBlock Text="{Binding Path=Author}" FontSize="16" Margin="15,0,0,0"/>
<TextBlock Text="{Binding Path=PubDate}" FontSize="16" Margin="15,0,0,0"/>
</StackPanel>
13.添加控件和內容
通過添加按鈕、列表、文本、圖形和圖像等控件創建應用的 UI。你所使用的元素取決於你的應用要完成的功能。
我們需要顯示一行文本(博客和文章標題)、多行文本(文章內容)和博客文章列表。我們通過添加TextBlock控件以顯示標題,
並且用一個ListView控件來顯示博客文章列表。初看之下,我們似乎可以使用一個多行的TextBlock或RichTextBlock來顯示文章內容。
但是,當我們更深入了解時,我們發現包含文章內容的字符串不是純文本,而是 HTML 字符串。我們不想顯示一堆 HTML 標記,
但如果我們將字符串放在一個 TextBlock 中便會發生這種情況,因此我們使用 WebView 控件來顯示 HTML。
Xmal代碼請參看12中的代碼。
14.顯示數據
a)使用值轉換器設置數據格式
在 ItemListView 的DataTemplate中,我們將PubDate屬性(是一個DateTime )綁定到TextBlock.Text屬性。
綁定引擎會自動將 PubDate 從一個 DateTime 轉換為一個字符串。但自動轉換會同時顯示日期和時間,
而我們只想顯示日期。要修復此問題,我們可以創建自己的值轉換器來將DateTime轉換為字符串,
並且可以在其中將字符串設置為任何需要的格式。要創建值轉換器,我們先創建一個用於實現IValueConverter接口的類,
然后實現Convert和ConvertBack方法。轉換器可以將數據從一種類型更改為另一種類型,根據文化背景轉換數據,
或者修改數據呈現方式的其他方面。在這里,我們創建一個日期轉換器,它將轉換傳入的日期值並設置其格式,從而只顯示日、月和年。
b)向項目添加值轉換器類,請選擇“項目”>“添加類”。將類命名為 DateConverter(.cs 或 .vb)。
Convert和ConvertBack方法還允許你傳入一個參數,以便通過不同的選項使用該轉換器的同一個實例。
在此示例中,我們包含了一個格式設置轉換器,它可以根據輸入的參數生成不同格式的日期。
你可以使用Binding類的ConverterParameter向Convert和ConvertBack方法中傳遞一個參數。代碼如下:

public class DateConverter:IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { if (value == null) throw new ArgumentNullException("value", "Value cannot be null."); if (!typeof(DateTime).Equals(value.GetType())) throw new ArgumentException("Value must be of type DateTime.", "value"); DateTime dt = (DateTime)value; if (parameter == null) { // Date "7/27/2011 9:30:59 AM" returns "7/27/2011" return DateTimeFormatter.ShortDate.Format(dt); } else if ((string)parameter == "day") { // Date "7/27/2011 9:30:59 AM" returns "27" DateTimeFormatter dateFormatter = new DateTimeFormatter("{day.integer(2)}"); return dateFormatter.Format(dt); } else if ((string)parameter == "month") { // Date "7/27/2011 9:30:59 AM" returns "JUL" DateTimeFormatter dateFormatter = new DateTimeFormatter("{month.abbreviated(3)}"); return dateFormatter.Format(dt).ToUpper(); } else if ((string)parameter == "year") { // Date "7/27/2011 9:30:59 AM" returns "2011" DateTimeFormatter dateFormatter = new DateTimeFormatter("{year.full}"); return dateFormatter.Format(dt); } else { // Requested format is unknown. Return in the original format. return dt.ToString(); } } public object ConvertBack(object value, Type targetType, object parameter, string language) { string strValue = value as string; DateTime resultDateTime; if (DateTime.TryParse(strValue, out resultDateTime)) { return resultDateTime; } return Windows.UI.Xaml.DependencyProperty.UnsetValue; } }
c)使用 DateConverter 類之前,必須在我們的 XAML 中聲明一個該類的實例。
我們將關鍵字 dateConverter 作為 App.xaml 中應用資源來聲明實例。在此處聲明實例后,在應用的每個頁面都可以使用它。
代碼如下:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!--
Styles that define common aspects of the platform look and feel
Required by Visual Studio project and item templates
-->
<ResourceDictionary Source="Common/StandardStyles.xaml">
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
<local:FeedDataSource x:Key="feedDataSource"/>
<local:DateConverter x:Key="dateConverter"/>
</ResourceDictionary>
</Application.Resources>
d)現在,我們便可在綁定中使用 DateConverter 了。以下是來自 ItemListView 的 DataTemplate 中更新后的 PubDate 綁定。
<TextBlock Text="{Binding PubDate,Converter={StaticResource dateConverter}}" FontSize="16" Margin="15,0,0,0"/>
15.在 WebView 中顯示 HTML
WebView 控件為我們提供了一種在應用內承載 HTML 數據的方法。但如果我們看看它的 Source 屬性,
就會發現它采用 Web 頁面的 Uri 進行顯示。我們的 HTML 數據只不過是HTML 的字符串。它沒有包含可以綁定到 Source 屬性的 Uri。
幸運的是,我們可以通過一種 NavigateToString 方法來傳遞我們的 HTML 字符串。
要實現該功能,我們需要處理ListView的SelectionChanged事件。
代碼如下:

private void ItemListView_SelectionChanged(object sender, SelectionChangedEventArgs e) { FeedItem feedItem = e.AddedItems[0] as FeedItem; if (feedItem!=null) { ContentView.NavigateToString(feedItem.Content); } }
16.現在我們的博客瀏覽器已基本成型,如下是界面截屏:
未完待續,敬請期待...