[源码下载]

重新想象 Windows 8 Store Apps (53) - 绑定: 与 ObservableCollection CollectionViewSource VirtualizedFilesVector VirtualizedItemsVector 绑定

作者:webabcd

介绍
重新想象 Windows 8 Store Apps 之 绑定

  • 与 ObservableCollection 绑定
  • 与 CollectionViewSource 绑定
  • 与 VirtualizedFilesVector 绑定
  • 对 VirtualizedItemsVector 绑定

示例
1、演示如何绑定 ObservableCollection<T> 类型的数据
Binding/BindingObservableCollection.xaml

<Page
x:Class="XamlDemo.Binding.BindingObservableCollection"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Binding"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"> <Grid Background="Transparent">
<Grid Margin="120 0 0 10"> <Grid.Resources>
<DataTemplate x:Key="MyDataTemplate">
<Border Background="Blue" Width="200" CornerRadius="3" HorizontalAlignment="Left">
<TextBlock Text="{Binding Name}" FontSize="14.667" />
</Border>
</DataTemplate>
</Grid.Resources> <StackPanel Orientation="Horizontal" VerticalAlignment="Top">
<Button Name="btnDelete" Content="删除一条记录" Click="btnDelete_Click_1" />
<Button Name="btnUpdate" Content="更新一条记录" Click="btnUpdate_Click_1" Margin="10 0 0 0" />
</StackPanel> <ListView x:Name="listView" ItemTemplate="{StaticResource MyDataTemplate}" Margin="0 50 0 0" /> </Grid>
</Grid>
</Page>

Binding/BindingObservableCollection.xaml.cs

/*
* 演示如何绑定 ObservableCollection<T> 类型的数据
*
* ObservableCollection<T> - 在数据集合进行添加项、删除项、更新项、移动项等操作时提供通知
* CollectionChanged - 当发生添加项、删除项、更新项、移动项等操作时所触发的事件(事件参数:NotifyCollectionChangedEventArgs)
*/ using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using XamlDemo.Model; namespace XamlDemo.Binding
{
public sealed partial class BindingObservableCollection : Page
{
private ObservableCollection<Employee> _employees; public BindingObservableCollection()
{
this.InitializeComponent(); this.Loaded += BindingObservableCollection_Loaded;
} void BindingObservableCollection_Loaded(object sender, RoutedEventArgs e)
{
_employees = new ObservableCollection<Employee>(TestData.GetEmployees());
_employees.CollectionChanged += _employees_CollectionChanged; listView.ItemsSource = _employees;
} void _employees_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
/*
* e.Action - 引发此事件的操作类型(NotifyCollectionChangedAction 枚举)
* Add, Remove, Replace, Move, Reset
* e.OldItems - Remove, Replace, Move 操作时影响的数据列表
* e.OldStartingIndex - Remove, Replace, Move 操作发生处的索引
* e.NewItems - 更改中所涉及的新的数据列表
* e.NewStartingIndex - 更改中所涉及的新的数据列表的发生处的索引
*/
} private void btnDelete_Click_1(object sender, RoutedEventArgs e)
{
_employees.RemoveAt();
} private void btnUpdate_Click_1(object sender, RoutedEventArgs e)
{
Random random = new Random(); // 此处的通知来自实现了 INotifyPropertyChanged 接口的 Employee
_employees.First().Name = random.Next(, ).ToString(); // 此处的通知来自 ObservableCollection<T>
_employees[] = new Employee() { Name = random.Next(, ).ToString() };
}
}
}

2、演示如何绑定 CollectionViewSource 类型的数据,以实现数据的分组显示
Binding/BindingCollectionViewSource.xaml

<Page
x:Class="XamlDemo.Binding.BindingCollectionViewSource"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Binding"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"> <Grid Background="Transparent">
<Grid Margin="120 0 0 10"> <ListView x:Name="listView">
<ListView.GroupStyle>
<GroupStyle>
<!--分组后,header 的数据模板-->
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title}" FontSize="24.667" />
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
<!--分组后,details 的数据模板-->
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title}" FontSize="14.667" Padding="50 0 0 0" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView> </Grid>
</Grid>
</Page>

Binding/BindingCollectionViewSource.xaml.cs

/*
* 演示如何绑定 CollectionViewSource 类型的数据,以实现数据的分组显示
*
* CollectionViewSource - 对集合数据启用分组支持
* Source - 数据源
* View - 获取视图对象,返回一个实现了 ICollectionView 接口的对象
* IsSourceGrouped - 数据源是否是一个被分组的数据
* ItemsPath - 数据源中,子数据集合的属性名称
*
* ICollectionView - 支持数据分组
* CollectionGroups - 组数据集合
*
*
* 注:关于数据分组的应用还可参见:XamlDemo/Index.xaml 和 XamlDemo/Index.xaml.cs
*/ using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data; namespace XamlDemo.Binding
{
public sealed partial class BindingCollectionViewSource : Page
{
public BindingCollectionViewSource()
{
this.InitializeComponent(); this.Loaded += BindingCollectionViewSource_Loaded;
} void BindingCollectionViewSource_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
XElement root = XElement.Load("SiteMap.xml");
var items = LoadData(root); // 构造数据源
CollectionViewSource groupData = new CollectionViewSource();
groupData.IsSourceGrouped = true;
groupData.Source = items;
groupData.ItemsPath = new PropertyPath("Items"); // 绑定 ICollectionView 类型的数据,以支持分组
listView.ItemsSource = groupData.View;
} // 获取数据
private List<GroupModel> LoadData(XElement root)
{
if (root == null)
return null; var items = from n in root.Elements("node")
select new GroupModel
{
Title = (string)n.Attribute("title"),
Items = LoadData(n)
}; return items.ToList();
} class GroupModel
{
public string Title { get; set; }
public List<GroupModel> Items { get; set; }
}
}
}

3、演示如何绑定 VirtualizedFilesVector
Binding/BindingVirtualizedFilesVector.xaml

<Page
x:Class="XamlDemo.Binding.BindingVirtualizedFilesVector"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Binding"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:converter="using:XamlDemo.Common"
mc:Ignorable="d"> <Grid Background="Transparent"> <Grid.Resources>
<converter:ThumbnailConverter x:Key="ThumbnailConverter"/>
<CollectionViewSource x:Name="itemsViewSource"/>
</Grid.Resources> <GridView Name="gridView" Padding="120 0 0 10" ItemsSource="{Binding Source={StaticResource itemsViewSource}}" SelectionMode="None">
<GridView.ItemTemplate>
<DataTemplate>
<Grid Width="160" Height="120">
<Border Background="Red" Width="160" Height="120">
<Image Source="{Binding Path=Thumbnail, Converter={StaticResource ThumbnailConverter}}" Stretch="None" Width="160" Height="120" />
</Border>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView> </Grid>
</Page>

Binding/BindingVirtualizedFilesVector.xaml.cs

/*
* 演示如何绑定 VirtualizedFilesVector
*
* 本 Demo 演示了如何将图片库中的文件绑定到 GridView
*/ using Windows.Storage;
using Windows.Storage.BulkAccess;
using Windows.Storage.FileProperties;
using Windows.Storage.Search;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation; namespace XamlDemo.Binding
{
public sealed partial class BindingVirtualizedFilesVector : Page
{
public BindingVirtualizedFilesVector()
{
this.InitializeComponent();
} protected override void OnNavigatedTo(NavigationEventArgs e)
{
QueryOptions queryOptions = new QueryOptions();
queryOptions.FolderDepth = FolderDepth.Deep;
queryOptions.IndexerOption = IndexerOption.UseIndexerWhenAvailable;
queryOptions.SortOrder.Clear();
SortEntry sortEntry = new SortEntry();
sortEntry.PropertyName = "System.FileName";
sortEntry.AscendingOrder = true;
queryOptions.SortOrder.Add(sortEntry); // 一个用于搜索图片库中的文件的查询
StorageFileQueryResult fileQuery = KnownFolders.PicturesLibrary.CreateFileQueryWithOptions(queryOptions); // 创建一个 FileInformationFactory 对象
var fileInformationFactory = new FileInformationFactory(fileQuery, ThumbnailMode.PicturesView, , ThumbnailOptions.UseCurrentScale, true); // 获取 VirtualizedFilesVector
itemsViewSource.Source = fileInformationFactory.GetVirtualizedFilesVector();
}
}
}

4、演示如何绑定 VirtualizedItemsVector
Binding/BindingVirtualizedItemsVector.xaml

<Page
x:Class="XamlDemo.Binding.BindingVirtualizedItemsVector"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Binding"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:converter="using:XamlDemo.Common"
mc:Ignorable="d"> <Grid Background="Transparent"> <Grid.Resources>
<converter:ThumbnailConverter x:Key="ThumbnailConverter"/>
<CollectionViewSource x:Name="itemsViewSource"/> <DataTemplate x:Key="FolderTemplate">
<Grid Width="160" Height="120">
<Border Background="Red" Width="160" Height="120">
<Image Source="{Binding Path=Thumbnail, Converter={StaticResource ThumbnailConverter}}" Stretch="None" Width="160" Height="120"/>
</Border>
<TextBlock Text="{Binding Name}" VerticalAlignment="Bottom" HorizontalAlignment="Center" Height="30" />
</Grid>
</DataTemplate>
<DataTemplate x:Key="FileTemplate">
<Grid Width="160" Height="120">
<Border Background="Red" Width="160" Height="120">
<Image Source="{Binding Path=Thumbnail, Converter={StaticResource ThumbnailConverter}}" Stretch="None" Width="160" Height="120"/>
</Border>
</Grid>
</DataTemplate> <local:FileFolderInformationTemplateSelector x:Key="FileFolderInformationTemplateSelector"
FileInformationTemplate="{StaticResource FileTemplate}"
FolderInformationTemplate="{StaticResource FolderTemplate}" />
</Grid.Resources> <GridView Name="gridView" Padding="120 0 0 10"
ItemsSource="{Binding Source={StaticResource itemsViewSource}}"
ItemTemplateSelector="{StaticResource FileFolderInformationTemplateSelector}"
SelectionMode="None">
</GridView> </Grid>
</Page>

Binding/BindingVirtualizedItemsVector.xaml.cs

/*
* 演示如何绑定 VirtualizedItemsVector
*
* 本 Demo 演示了如何将图片库中的顶级文件夹和顶级文件绑定到 GridView,同时演示了如何 runtime 时选择模板
*/ using Windows.Storage;
using Windows.Storage.BulkAccess;
using Windows.Storage.FileProperties;
using Windows.Storage.Search;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation; namespace XamlDemo.Binding
{
public sealed partial class BindingVirtualizedItemsVector : Page
{
public BindingVirtualizedItemsVector()
{
this.InitializeComponent();
} protected override void OnNavigatedTo(NavigationEventArgs e)
{
QueryOptions queryOptions = new QueryOptions();
queryOptions.FolderDepth = FolderDepth.Shallow;
queryOptions.IndexerOption = IndexerOption.UseIndexerWhenAvailable;
queryOptions.SortOrder.Clear();
SortEntry sortEntry = new SortEntry();
sortEntry.PropertyName = "System.IsFolder";
sortEntry.AscendingOrder = false;
queryOptions.SortOrder.Add(sortEntry);
SortEntry sortEntry2 = new SortEntry();
sortEntry2.PropertyName = "System.ItemName";
sortEntry2.AscendingOrder = true;
queryOptions.SortOrder.Add(sortEntry2); // 一个用于搜索图片库中的顶级文件夹和顶级文件的查询
StorageItemQueryResult itemQuery = KnownFolders.PicturesLibrary.CreateItemQueryWithOptions(queryOptions); // 创建一个 FileInformationFactory 对象
var fileInformationFactory = new FileInformationFactory(itemQuery, ThumbnailMode.PicturesView, , ThumbnailOptions.UseCurrentScale, true); // 获取 VirtualizedItemsVector
itemsViewSource.Source = fileInformationFactory.GetVirtualizedItemsVector();
}
} // 继承 DataTemplateSelector 以实现 runtime 时选择模板
public class FileFolderInformationTemplateSelector : DataTemplateSelector
{
// 显示文件时的模板
public DataTemplate FileInformationTemplate { get; set; } // 显示文件夹时的模板
public DataTemplate FolderInformationTemplate { get; set; } // 根据 item 的类型选择指定的模板
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
var folder = item as FolderInformation;
if (folder == null)
return FileInformationTemplate;
else
return FolderInformationTemplate;
}
}
}

OK
[源码下载]

重新想象 Windows 8 Store Apps (53) - 绑定: 与 ObservableCollection CollectionViewSource VirtualizedFilesVector VirtualizedItemsVector 绑定的更多相关文章

  1. 重新想象 Windows 8 Store Apps 系列文章索引

    [源码下载][重新想象 Windows 8.1 Store Apps 系列文章] 重新想象 Windows 8 Store Apps 系列文章索引 作者:webabcd 1.重新想象 Windows ...

  2. 重新想象 Windows 8 Store Apps (52) - 绑定: 与 Element Model Indexer Style RelativeSource 绑定, 以及绑定中的数据转换

    [源码下载] 重新想象 Windows 8 Store Apps (52) - 绑定: 与 Element Model Indexer Style RelativeSource 绑定, 以及绑定中的数 ...

  3. 重新想象 Windows 8 Store Apps (54) - 绑定: 增量方式加载数据

    [源码下载] 重新想象 Windows 8 Store Apps (54) - 绑定: 增量方式加载数据 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 绑定 通过实 ...

  4. 重新想象 Windows 8 Store Apps (55) - 绑定: MVVM 模式

    [源码下载] 重新想象 Windows 8 Store Apps (55) - 绑定: MVVM 模式 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 绑定 通过 M ...

  5. 重新想象 Windows 8 Store Apps (59) - 锁屏

    [源码下载] 重新想象 Windows 8 Store Apps (59) - 锁屏 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 锁屏 登录锁屏,获取当前程序的锁 ...

  6. 重新想象 Windows 8 Store Apps (15) - 控件 UI: 字体继承, Style, ControlTemplate, SystemResource, VisualState, VisualStateManager

    原文:重新想象 Windows 8 Store Apps (15) - 控件 UI: 字体继承, Style, ControlTemplate, SystemResource, VisualState ...

  7. 重新想象 Windows 8 Store Apps (16) - 控件基础: 依赖属性, 附加属性, 控件的继承关系, 路由事件和命中测试

    原文:重新想象 Windows 8 Store Apps (16) - 控件基础: 依赖属性, 附加属性, 控件的继承关系, 路由事件和命中测试 [源码下载] 重新想象 Windows 8 Store ...

  8. 重新想象 Windows 8 Store Apps (13) - 控件之 SemanticZoom

    原文:重新想象 Windows 8 Store Apps (13) - 控件之 SemanticZoom [源码下载] 重新想象 Windows 8 Store Apps (13) - 控件之 Sem ...

  9. 重新想象 Windows 8 Store Apps (12) - 控件之 GridView 特性: 拖动项, 项尺寸可变, 分组显示

    原文:重新想象 Windows 8 Store Apps (12) - 控件之 GridView 特性: 拖动项, 项尺寸可变, 分组显示 [源码下载] 重新想象 Windows 8 Store Ap ...

随机推荐

  1. nlog(n)解动态规划--最长上升子序列(Longest increasing subsequence)

    最长上升子序列LIS问题属于动态规划的初级问题,用纯动态规划的方法来求解的时间复杂度是O(n^2).但是如果加上二叉搜索的方法,那么时间复杂度可以降到nlog(n).  具体分析参考:http://b ...

  2. 【AI】蒙特卡洛搜索树

    http://jeffbradberry.com/posts/2015/09/intro-to-monte-carlo-tree-search/ 蒙特卡洛方法与随机优化: http://iacs-co ...

  3. AngularJs解决方案笔记(1)

    接触AngularJs约1年半时间,目前用其独立完成了一个Solution, 构建出比较完整的项目架构,从C/S往B/S转型的过程背后是大量精力与时间成本的付出,特别是工作了好几年后, 本来掌握好的稳 ...

  4. Fabric自动部署太方便了

    之前不知道有Fabric工具,每次发布程序到服务器上的时候,基本流程:本地打包程序 -> Ftp上传 -> 停服务器Apache -> 覆盖文件 -> 启动Apache, 非常 ...

  5. 说说lambda表达式与表达式树(未完)

    Lambda表达式可以转换成为代码(委托)或者数据(表达式树).若将其赋值给委托,则Lambda表达式将转换为IL代码:如果赋值给 Expression<TDelegate>,则构造出一颗 ...

  6. 如何在wp8 中调试cocos2dx c++ 代码

    有的时候在win32上运行良好的cocos2dx程序移植到wp8的时候就出了问题,我们想把断点放到c++代码中,需要设置一下VS 2012 右击项目属性 把ui任务 设置为仅限本机 即可.

  7. 免费国内外"代码托管服务器"收集

      国内 开源中国  http://git.oschina.net/  支持git 淘宝code  http://code.taobao.org/  支持svn 京东code  https://cod ...

  8. oracle create table(转)

    //建测试表 create table dept( deptno number(3) primary key, dname varchar2(10), loc varchar2(13) ); crea ...

  9. CentOS 6上安装xfce桌面环境

    [日期:2012-01-30]   在新的CentOS 6上默认没有包含xfce的桌面环境,使用yum也找不到这些包,但是自己又喜欢这种简单的桌面环境,此时可以使用下面的方法来安装 [plain] $ ...

  10. Safari下默认10位数字为电话号码,点击拨号

    <meta content="telephone=no" name="format-detection"/>