WPF 数据绑定 定制一个集合的视图 导航

来源:互联网 发布:网络时间现在几点 编辑:程序博客网 时间:2024/06/05 17:02

导航

对视图进行导航是说管理当前项。

/* 注意:直到源集合中某一项被选中前,CurrentItem始终为null,CurrentPosition则为-1 *///上一页private void NavigatedPrevious(){    ICollectionView view = CollectionViewSource.GetDefaultView(pl);    //向后移动    view.MoveCurrentToPrevious();    //循环,回到最后一项    if (view.IsCurrentBeforeFirst)    {        view.MoveCurrentToLast();    }}//下一页private void NavigatedNext(){    ICollectionView view = CollectionViewSource.GetDefaultView(pl);    //向前移动    view.MoveCurrentToNext();    //循环,回到第一项    if (view.IsCurrentAfterLast)    {        view.MoveCurrentToFirst();    }}


使用其他视图

之前的排序,分组等操作都是与源集合关联的默认视图,可以通过CollectionViewSource构造一个新视图,选择性的应用到任何目标。

namespace WPF_Test{    /// <summary>    /// BindPage.xaml 的交互逻辑    /// </summary>    public partial class BindPage : Page    {        public BindPage()        {            //将数据源添加到当前页的逻辑资源中              //Resources.Add("photoList", pl);            InitializeComponent();            PhotoList pl = this.Resources["pl"] as PhotoList;            pl.Add(new PhotoModel("img/a.jpg", "a.jpg", 1, Convert.ToDateTime("2011/09/01")));            pl.Add(new PhotoModel("img/b.jpg", "b.jpg", 2, Convert.ToDateTime("2011/09/01")));            pl.Add(new PhotoModel("img/c.jpg", "c.jpg", 3, Convert.ToDateTime("2011/09/03")));            //创建一个自定义的CollectionViewSource            CollectionViewSource viewSource = new CollectionViewSource();            viewSource.Source = pl;        }    }}
<Page x:Class="WPF_Test.BindPage"      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"       xmlns:d="http://schemas.microsoft.com/expression/blend/2008"      xmlns:custom="clr-namespace:WPF_Test"        mc:Ignorable="d"       d:DesignHeight="300" d:DesignWidth="300"  Title="BindPage"><Page.Resources>        <custom:PhotoList x:Key="pl"/>    <!-- 配置自定义视图,实现排序,分组,过滤 -->    <CollectionViewSource x:Key="MyViewSource" Source="{StaticResource pl}" Filter="FilterFun">        <!-- 需引入xmlns:componentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase" -->        <!-- 排序 -->        <CollectionViewSource.SortDescriptions>            <componentModel:SortDescription PropertyName="Name" Direction="Descending"/>         </CollectionViewSource.SortDescriptions>        <!-- 分组 -->        <CollectionViewSource.GroupDescriptions>            <PropertyGroupDescription PropertyName="DateTime"/>        </CollectionViewSource.GroupDescriptions>    </CollectionViewSource></Page.Resources><StackPanel>    <ListBox x:Name="listBox1" SelectedValuePath="Name"     ItemsSource="{Binding Source={StaticResource MyViewSource}}" /></StackPanel> </Page>