如何动态绑定Pivot项,即PiovtItem的项是动态的

来源:互联网 发布:数据库管理员能干什么 编辑:程序博客网 时间:2024/04/28 18:14

前几天有个网友问我如何动态绑定Pivot项,即PiovtItem的项是动态的,PivotItem中的数据也是动态的。这个使用MVVM模式可以很方便的实现,在ViewModel中设置一个集合表示当前有多少个Item,集合中的类中含有当前PivotItem中的数据源。下面以一个简单的demo来演示下:

先来看看XAML中是怎么去绑定的

<!--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模板,这两个模板分别如下:

<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下的ListData

ViewModel中的数据源:

private ObservableCollection<TestPivot> _bindData;public ObservableCollection<TestPivot> BindData{    get    {        return _bindData;    }    set    {        _bindData = value;        RaisePropertyChanged("BindData");    }}

TestPivot即自己定义的类,含有PiovtHeader和PivotItem数据源的类:

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,绑定已经建立好了,现在就是如何初始化数据源了,为了简单起见,以最简单的循环生成绑定源数据:

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);    }}