Windows 8中的GridView使用(二)和DataTemplateSelector
在本文中所講述內容的執行個體仍然沿用於上篇文章,有什麼疑惑可以參考上篇文章。
一 GroupStyle 在GridView控制項中我們可以對資料進行分組顯示,通過對GridView的GroupStyle進行控制,分別設定 GroupStyle.HeaderTemplate和GroupStyle.Panel。如下代碼:
<GridView.GroupStyle> <GroupStyle> <GroupStyle.HeaderTemplate> <DataTemplate> <Grid Margin="1,0,0,6"> <Button AutomationProperties.Name="組名稱" Content="{Binding GroupTitle}"/> </Grid> </DataTemplate> </GroupStyle.HeaderTemplate> <GroupStyle.Panel> <ItemsPanelTemplate> <VariableSizedWrapGrid Orientation="Vertical" Margin="0,0,50,0"/> </ItemsPanelTemplate> </GroupStyle.Panel> </GroupStyle> </GridView.GroupStyle>
二 DataTemplateSelector 在不同的組之間我們想使 用不同的樣式進行顯示,在這裡我們可以繼承重寫DataTemplateSelector類編寫並且根據後台資料選擇相應的 樣式模版進行呈現。
在之前代碼的基礎上我們需要做以下工作:
1.編寫一個類繼承於 DataTemplateSelector
public class TemplateSelector : DataTemplateSelector { /// <summary> /// 第一種文本顯示模版 /// </summary> public DataTemplate TextBoxTemplate { get; set; } /// <summary> /// 第二種圖片為主顯示模版 /// </summary> public DataTemplate ImageTemplate { get; set; } /// <summary> /// 核心方法:根據不同的資料來源類型返回給前台不同的樣式模版 /// </summary> /// <param name="item"></param> /// <param name="container"></param> /// <returns></returns> protected override DataTemplate SelectTemplateCore(object item, DependencyObject container) { DataModel model = item as DataModel; string typeName = model.MainModel.Name; if (typeName == typeof(TextBox).Name)//根據資料來源設定的資料顯示模式返回前台樣式模版 { return TextBoxTemplate; } if (typeName == typeof(Image).Name) { return ImageTemplate; } return null; } }