Windows Phone 实用开发技巧(29):动态绑定Pivot

本文介绍了一种使用MVVM模式动态绑定Pivot项的方法。通过设置ViewModel中的集合表示PivotItem的数量及其数据源,实现了PivotItem的动态加载。文章提供了XAML绑定代码示例及数据初始化方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

其中size表示当前有几个PivotItem,这里Pivot数据源可以是同步方式也可以以异步方式,只要TestPivot实现NotifyPropertyChanged,并且属性ListData通知改变即可。

你可以从这里找到源代码, Hope that helps.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值