您的位置:首页 > 其它

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

2011-11-20 07:44 399 查看
前几天有个网友问我如何动态绑定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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐