前幾天有個網友問我如何動態綁定Pivot項,即PiovtItem的項是動態 的,PivotItem中的數據也是動態的。這個使用MVVM模式能夠很方便的實現,在ViewModel中設置一個集合表示當前有多少個Item,集合 中的類中含有當前PivotItem中的數據源。下面以一個簡單的demo來演示下:異步
先來看看XAML中是怎麼去綁定的ide
<!--LayoutRoot is the root grid where all page content is placed--> <Grid x:Name="LayoutRoot" Background="Transparent"> <!--Pivot Control--> <controls:Pivot Title="MY APPLICATION" ItemTemplate="{StaticResource DT_Pivot}" HeaderTemplate="{StaticResource DT_Header}" ItemsSource="{Binding BindData}"> </controls:Pivot> </Grid>
Pivot的數據源綁定是ViewModel中的BindData,ItemTemplate表示PivotItem的模板,HeaderTemplate表示PivotItem中Header模板,這兩個模板分別以下:post
<phone:PhoneApplicationPage.Resources> <DataTemplate x:Key="DT_Pivot"> <ListBox ItemsSource="{Binding ListData}"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </DataTemplate> <DataTemplate x:Key="DT_Header"> <TextBlock Text="{Binding Name}" /> </DataTemplate> </phone:PhoneApplicationPage.Resources>
HeaderTemplate十分簡單,就使用一個TextBlock表示當前的標題。Pivot的ItemTemplate裏面放置一個ListBox,數據源爲BindData下的ListDataspa
ViewModel中的數據源:code
private ObservableCollection<TestPivot> _bindData; public ObservableCollection<TestPivot> BindData { get { return _bindData; } set { _bindData = value; RaisePropertyChanged("BindData"); } }
TestPivot即本身定義的類,含有PiovtHeader和PivotItem數據源的類:blog
public class TestPivot { /// <summary> /// property for pivot header /// </summary> public string Name { get; set; } /// <summary> /// data for pivot item datasource(eg.listbox) /// </summary> public List<string> ListData { get; set; } }
ok,綁定已經創建好了,如今就是如何初始化數據源了,爲了簡單起見,以最簡單的循環生成綁定源數據:get
public void AddData(int size) { BindData = new ObservableCollection<TestPivot>(); for (int i = 0; i < size; i++) { TestPivot t = new TestPivot(); t.Name = "piovt item" + i; t.ListData = new List<string>(); for (int j = 0; j < 10; j++) { t.ListData.Add("List item"+j); } BindData.Add(t); } }
其中size表示當前有幾個PivotItem,這裏Pivot數據源能夠是同步方式也能夠以異步方式,只要TestPivot實現NotifyPropertyChanged,而且屬性ListData通知改變便可。同步
你能夠從這裏找到源代碼, Hope that helps.string