介紹
重新想象 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() }; } }}