重新想象 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(0); } private void btnUpdate_Click_1(object sender, RoutedEventArgs e) { Random random = new Random(); // 此处的通知来自实现了 INotifyPropertyChanged 接口的 Employee _employees.First().Name = random.Next(1000, 10000).ToString(); // 此处的通知来自 ObservableCollection<T> _employees[1] = new Employee() { Name = random.Next(1000, 10000).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, 160, 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, 160, 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
[源码下载]
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。