前几天有个网友问我如何动态绑定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