Architect's Log

I'm a Cloud Architect. I'm highly motivated to reduce toils with driving DevOps.

CollectionViewSourceを使ってコレクションビューを実装する

アプリ実行


ソースコード

App.xaml
<Application x:Class="WpfApplication8.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
</Application>
MainWindow.xaml
<Window x:Class="WpfApplication8.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <CollectionViewSource x:Key="customView">
            <!-- Ageの昇順でソート -->
            <CollectionViewSource.SortDescriptions>
                <scm:SortDescription
                    PropertyName="Age"
                    Direction="Ascending" />
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>
    </Window.Resources>
    <ListBox
        ItemsSource="{Binding Source={StaticResource customView}}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Path=Name}" />
                    <TextBlock Text=" " />
                    <TextBlock Text="{Binding Path=Age}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Window>
MainWindow.xaml.cs
using System.Windows;
using System.Windows.Data;

namespace WpfApplication8 {
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();

            CollectionViewSource viewSource = (CollectionViewSource) this.Resources["customView"];
            viewSource.Source = new Person[] {
                new Person() { Name = "佐藤太郎", Age = 21 },
                new Person() { Name = "鈴木次郎", Age = 20 }
            };
        }
    }
}
Person.cs
namespace WpfApplication8 {
    class Person {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

参考

CollectionViewSource クラス (System.Windows.Data)
CollectionView クラスの Extensible Application Markup Language (XAML) プロキシ。