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


[源碼下載]


重新想象 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
[源碼下載]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM