かずきのBlog

C#やJavaやRubyとメモ書き

目次

Blog 利用状況

ニュース

わんくまBlogが不安定になったため、前に書いてたはてなダイアリーにメインを移動します。
かずきのBlog@Hatena
技術的なネタは、こちらにも、はてなへのリンクという形で掲載しますが、雑多ネタははてなダイアリーだけに掲載することが多いと思います。
コメント
プログラマ的自己紹介
お気に入りのツール/IDE
プロフィール
経歴
広告
アクセサリ

書庫

日記カテゴリ

[WPF][C#]ListBoxのデータをソートしたい

タイトルのままですが、WPFのListBoxにバインドしたデータをソートして表示したい!という状況にある前提で話をします。しかも、取得できるデータは目的の形にソートされていないという、最低の状態のところからスタートします。

下準備

とりあえず、表示するデータが単一の値だとつまらないので、適当なクラスをでっちあげます。名前と年齢を持つPersonクラスを下のように定義します。データ取得用のメソッドもPersonクラスのstaticなメソッドとして定義しています。

using System;
using System.Linq;

namespace WpfListBoxSort
{
    // 人間
    public class Person
    {
        // 年齢
        public int Age { get; set; }
        // 名前
        public string Name { get; set; }

        /// <summary>
        /// 引数で渡された人数のPersonオブジェクトを生成して返す。
        /// 年齢は、0~99才までのランダムに生成される。
        /// </summary>
        public static Person[] GetPeople(int count)
        {
            Random r = new Random();
            // 無理やりLINQ使った
            return (from val in Enumerable.Range(1, count)
                    select new Person { Name = val + "太郎", Age = r.Next(100) }).ToArray();
        }
    }
}

ここまで準備できたら、画面を作りにはいる。画面は、上部にデータ取得のためのボタン。残りの部分いっぱいにListBoxが表示されるといった感じで作ってみた。下記にXAML部分のコードを示す。

<Window x:Class="WpfListBoxSort.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <DockPanel>
        <Button DockPanel.Dock="Top" Content="Generate Data" Click="Button_Click" />
        <ListBox />
    </DockPanel>
</Window>

実行結果は下の通り。
image

今のところ、取り立てて珍しいことは無い。これで下地が出来たので、ListBoxのデータのソートに入ろうと思う。

ソートするよ

さて、配列なListをWPFのBindingを使ってItemsSourceプロパティにバインドすると、裏ではCollectionViewSourceというクラスが使われてたりする。こいつは、DataTableとDataViewの対応に近い。実データの上に薄くかぶさってソート等の処理をやってくれる。CollectionViewSourceを使うと、指定したプロパティでソートしたり出来る。
今回は、XAMLでCollectionViewSourceを直接定義して使ってみようと思う。

まず、データ表示の大元になるObjectDataProviderの定義をWindow.Resourcesに追加する。

<Window x:Class="WpfListBoxSort.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:WpfListBoxSort="clr-namespace:WpfListBoxSort"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <ObjectDataProvider x:Key="PeopleDataProvider" 
                            IsInitialLoadEnabled="False"
                            ObjectType="{x:Type WpfListBoxSort:Person}" 
                            MethodName="GetPeople" />
    </Window.Resources>
    <!-- さっきと一緒なので以下は省略 -->
</Window>

次に、このDataProviderをもとにCollectionViewSourceの定義を追加する。

        <!-- CollectionViewSourceの定義 データの元はPeopleDataProvider -->
        <CollectionViewSource x:Key="PeopleViewSource" Source="{StaticResource PeopleDataProvider}">
            <!-- Nameプロパティで昇順でソート -->
            <CollectionViewSource.SortDescriptions>
                <ComponentModel:SortDescription PropertyName="Age" Direction="Ascending" />
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>

上のXAMLでしているように、CollectionViewSourceのCollectionViewSource.SortDescriptionsにソートの定義を追加していくとソートできる。何故かSortDescriptionsに入れるSortDescriptionはWindowsBaseのSystem.ComponentModelにあるので何処かで「xmlns:ComponentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase"」を定義しないといけないので注意。

CollectionViewSourceが出来たので、ListBoxにバインドする。

<ListBox ItemsSource="{Binding Source={StaticResource PeopleViewSource}}"/>

そして、ボタンのクリックイベントで、DataProviderにデータの取得をお願いします。

private void Button_Click(object sender, RoutedEventArgs e)
{
    var random = new Random();

    var dataProvider = (ObjectDataProvider) FindResource("PeopleDataProvider");
    dataProvider.MethodParameters.Clear();
    dataProvider.MethodParameters.Add(random.Next(100));
    dataProvider.Refresh();
}

これで、データがソートされて表示されますが・・・!!DataTemplateを定義してないので下のように表示されてがっかりorzしてしまいます。

image

ということで、DataTemplateの定義を下でやりたいと思います。Window.Resourcesに定義を足す形で書きます。

        <DataTemplate DataType="{x:Type WpfListBoxSort:Person}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Name}" />
                <TextBlock Text="さん " />
                <TextBlock Text="{Binding Age}" />
                <TextBlock Text="才" />
            </StackPanel>
        </DataTemplate>

これでめでたくListBoxにデータがソートされて出力されます。ボタンを押してデータを取り直してもばっちりソートされてる。
image image

めでたしめでたし。

投稿日時 : 2008年8月5日 23:25

Feedback

# lancel 2012/10/17 23:20 http://www.saclancelpascher2013.com

I like this post, enjoyed this one thanks for putting up.

# Cheap Air Jordan 4 Retro 2012/12/08 8:35 http://suparjordanshoes.webs.com/

I dugg some of you post as I cerebrated they were handy handy

# longchamp soldes 2012/12/15 15:24 http://www.soldesacslongchamp.info/category/longch

If ones own photostream features photos of which - irrespective of whether good and / or not : triggered a spirited comments¡ä line.

# burberry uk 2012/12/15 23:03 http://www.burberryuksale.org

I won't know... there's a little something tacky related to owning Ferrari branded things like this.. unless moreover, you may own a genuine Ferrari.

# sac longchamp france 2012/12/17 2:56 http://www.longchampfr.info/category/solde-longcha

Thus, our shelves wind up filled with items that we take pleasure in.

# hermes pairs 2012/12/17 20:05 http://www.hermespairs.info/category/エルメス

Nobody will probably see yourself to mug you from your basement.

# burberry sale 2012/12/18 14:26 http://www.burberryuksale.org/category/burberry-ou

I work with earbuds away from home because from the portability, even though I favor over the actual ear.

# scarf burberry online 2012/12/18 20:16 http://www.burberryoutlet2012.info/category/burber

Our pool really should be fed with those photopages that you really consider valued at becoming the main "Best Provide feedback Collection".

# casquette enfant 2013/03/23 21:22 http://f44.fr/

Once you would certainly maintain your tip by an opponent, explain keep in mind this do not a colleague. casquette enfant http://f44.fr/

# casquette volcom 2013/03/23 21:24 http://f22.fr/

Affection is definitely the dynamic situation to the lifespan therefore the expansion of whatever most people absolutely love. casquette volcom http://f22.fr/

# f44.fr 2013/03/23 21:25 http://f44.fr/

When successfulness this family and friends learn everyone; when it comes to trouble we all know this family and friends. f44.fr http://f44.fr/

# destockchine 2013/03/24 0:37 http://d77.fr/

Most likely Who intends america to meet a few inappropriate men or women prior to getting together the right one, make certain that back when we conclusively satisfy the man, analysis discover how to possibly be pleased. destockchine http://d77.fr/

# usine23 2013/03/24 0:37 http://e55.fr/

Romance will be the lone sane and also fine solution among a person's survival. usine23 http://e55.fr/

# destockchine 2013/03/24 0:38 http://c99.fr/

Appreciate is without a doubt frail on inception, having said that it will grow tougher with each passing year if it is carefully provided. destockchine http://c99.fr/

# Laredoute 2013/04/07 5:10 http://ruezee.com/

Around the world may well anyone, on the other hand to one woman may well society. Laredoute http://ruezee.com/

# coach outlet purses 2013/04/07 17:10 http://www.coachoutletstore55.com/

Pleasure is definitely a aroma you can not rain cats and dogs concerning the rest without having choosing a couple of sheds concerning your own. coach outlet purses http://www.coachoutletstore55.com/

# tati 2013/04/08 0:32 http://ruenee.com/

A honest good friend . is that overlooks your flops and thus can handle your successes. tati http://ruenee.com/

# chaussea 2013/04/08 5:38 http://ruemee.com/

One particular sibling probably are not partner, yet partner have invariably been the sibling. chaussea http://ruemee.com/

# YMWsYTnLCuBYAwHTq 2015/04/19 17:43 sally

O2ja1K http://www.FyLitCl7Pf7kjQdDUOLQOuaxTXbj5iNG.com

# Heya i'm for the first time here. I found this board and I to find It truly useful & it helped me out a lot. I hope to provide one thing again and help others such as you helped me. 2021/08/29 0:26 Heya i'm for the first time here. I found this boa

Heya i'm for the first time here. I found this board and I to find It truly useful & it helped me
out a lot. I hope to provide one thing again and help
others such as you helped me.

# Heya i'm for the first time here. I found this board and I to find It truly useful & it helped me out a lot. I hope to provide one thing again and help others such as you helped me. 2021/08/29 0:27 Heya i'm for the first time here. I found this boa

Heya i'm for the first time here. I found this board and I to find It truly useful & it helped me
out a lot. I hope to provide one thing again and help
others such as you helped me.

# Heya i'm for the first time here. I found this board and I to find It truly useful & it helped me out a lot. I hope to provide one thing again and help others such as you helped me. 2021/08/29 0:28 Heya i'm for the first time here. I found this boa

Heya i'm for the first time here. I found this board and I to find It truly useful & it helped me
out a lot. I hope to provide one thing again and help
others such as you helped me.

# Heya i'm for the first time here. I found this board and I to find It truly useful & it helped me out a lot. I hope to provide one thing again and help others such as you helped me. 2021/08/29 0:29 Heya i'm for the first time here. I found this boa

Heya i'm for the first time here. I found this board and I to find It truly useful & it helped me
out a lot. I hope to provide one thing again and help
others such as you helped me.

# Hurrah, that's what I was looking for, what a stuff! existing here at this website, thanks admin of this website. 2021/09/02 2:28 Hurrah, that's what I was looking for, what a stuf

Hurrah, that's what I was looking for, what a stuff!

existing here at this website, thanks admin of this website.

# Hurrah, that's what I was looking for, what a stuff! existing here at this website, thanks admin of this website. 2021/09/02 2:29 Hurrah, that's what I was looking for, what a stuf

Hurrah, that's what I was looking for, what a stuff!

existing here at this website, thanks admin of this website.

# Hurrah, that's what I was looking for, what a stuff! existing here at this website, thanks admin of this website. 2021/09/02 2:30 Hurrah, that's what I was looking for, what a stuf

Hurrah, that's what I was looking for, what a stuff!

existing here at this website, thanks admin of this website.

# Hurrah, that's what I was looking for, what a stuff! existing here at this website, thanks admin of this website. 2021/09/02 2:31 Hurrah, that's what I was looking for, what a stuf

Hurrah, that's what I was looking for, what a stuff!

existing here at this website, thanks admin of this website.

# This piece of writing will help the internet viewers for building up new web site or even a blog from start to end. 2021/09/03 17:41 This piece of writing will help the internet viewe

This piece of writing will help the internet viewers for building up new
web site or even a blog from start to end.

# This piece of writing will help the internet viewers for building up new web site or even a blog from start to end. 2021/09/03 17:42 This piece of writing will help the internet viewe

This piece of writing will help the internet viewers for building up new
web site or even a blog from start to end.

# This piece of writing will help the internet viewers for building up new web site or even a blog from start to end. 2021/09/03 17:43 This piece of writing will help the internet viewe

This piece of writing will help the internet viewers for building up new
web site or even a blog from start to end.

# This piece of writing will help the internet viewers for building up new web site or even a blog from start to end. 2021/09/03 17:44 This piece of writing will help the internet viewe

This piece of writing will help the internet viewers for building up new
web site or even a blog from start to end.

# Pretty! This has been an extremely wonderful post. Thanks for supplying these details. 2021/09/04 21:42 Pretty! This has been an extremely wonderful post.

Pretty! This has been an extremely wonderful post.
Thanks for supplying these details.

# Pretty! This has been an extremely wonderful post. Thanks for supplying these details. 2021/09/04 21:43 Pretty! This has been an extremely wonderful post.

Pretty! This has been an extremely wonderful post.
Thanks for supplying these details.

# Pretty! This has been an extremely wonderful post. Thanks for supplying these details. 2021/09/04 21:44 Pretty! This has been an extremely wonderful post.

Pretty! This has been an extremely wonderful post.
Thanks for supplying these details.

# Pretty! This has been an extremely wonderful post. Thanks for supplying these details. 2021/09/04 21:45 Pretty! This has been an extremely wonderful post.

Pretty! This has been an extremely wonderful post.
Thanks for supplying these details.

# Heya i'm for the first time here. I came across this board and I find It really useful & it helped me out much. I hope to give something back and aid others like you helped me. ps4 https://bit.ly/3z5HwTp ps4 2021/09/12 23:55 Heya i'm for the first time here. I came across th

Heya i'm for the first time here. I came across this board and I find It really useful & it helped me out much.
I hope to give something back and aid others like you helped me.
ps4 https://bit.ly/3z5HwTp ps4

# Heya i'm for the first time here. I came across this board and I find It really useful & it helped me out much. I hope to give something back and aid others like you helped me. ps4 https://bit.ly/3z5HwTp ps4 2021/09/12 23:56 Heya i'm for the first time here. I came across th

Heya i'm for the first time here. I came across this board and I find It really useful & it helped me out much.
I hope to give something back and aid others like you helped me.
ps4 https://bit.ly/3z5HwTp ps4

# Heya i'm for the first time here. I came across this board and I find It really useful & it helped me out much. I hope to give something back and aid others like you helped me. ps4 https://bit.ly/3z5HwTp ps4 2021/09/12 23:57 Heya i'm for the first time here. I came across th

Heya i'm for the first time here. I came across this board and I find It really useful & it helped me out much.
I hope to give something back and aid others like you helped me.
ps4 https://bit.ly/3z5HwTp ps4

# Heya i'm for the first time here. I came across this board and I find It really useful & it helped me out much. I hope to give something back and aid others like you helped me. ps4 https://bit.ly/3z5HwTp ps4 2021/09/12 23:58 Heya i'm for the first time here. I came across th

Heya i'm for the first time here. I came across this board and I find It really useful & it helped me out much.
I hope to give something back and aid others like you helped me.
ps4 https://bit.ly/3z5HwTp ps4

# For the reason that the admin of this web site is working, no hesitation very shortly it will be renowned, due to its feature contents. quest bars https://www.iherb.com/search?kw=quest%20bars quest bars 2021/09/14 8:42 For the reason that the admin of this web site is

For the reason that the admin of this web site
is working, no hesitation very shortly it will be renowned, due to its feature
contents. quest bars https://www.iherb.com/search?kw=quest%20bars quest bars

# For the reason that the admin of this web site is working, no hesitation very shortly it will be renowned, due to its feature contents. quest bars https://www.iherb.com/search?kw=quest%20bars quest bars 2021/09/14 8:43 For the reason that the admin of this web site is

For the reason that the admin of this web site
is working, no hesitation very shortly it will be renowned, due to its feature
contents. quest bars https://www.iherb.com/search?kw=quest%20bars quest bars

# For the reason that the admin of this web site is working, no hesitation very shortly it will be renowned, due to its feature contents. quest bars https://www.iherb.com/search?kw=quest%20bars quest bars 2021/09/14 8:44 For the reason that the admin of this web site is

For the reason that the admin of this web site
is working, no hesitation very shortly it will be renowned, due to its feature
contents. quest bars https://www.iherb.com/search?kw=quest%20bars quest bars

# For the reason that the admin of this web site is working, no hesitation very shortly it will be renowned, due to its feature contents. quest bars https://www.iherb.com/search?kw=quest%20bars quest bars 2021/09/14 8:45 For the reason that the admin of this web site is

For the reason that the admin of this web site
is working, no hesitation very shortly it will be renowned, due to its feature
contents. quest bars https://www.iherb.com/search?kw=quest%20bars quest bars

# you are really a just right webmaster. The website loading speed is incredible. It sort of feels that you're doing any unique trick. Furthermore, The contents are masterwork. you've done a great task in this subject! 2021/10/26 2:27 you are really a just right webmaster. The website

you are really a just right webmaster. The website loading speed is incredible.

It sort of feels that you're doing any unique trick. Furthermore, The contents
are masterwork. you've done a great task in this subject!

# Hello there! Do you know if they make any plugins to assist with Search Engine Optimization? I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good success. If you know of any please share. Appreciate it! 2021/11/12 17:23 Hello there! Do you know if they make any plugins

Hello there! Do you know if they make any plugins to assist with Search Engine
Optimization? I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good success.
If you know of any please share. Appreciate it!

# Hello there! Do you know if they make any plugins to assist with Search Engine Optimization? I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good success. If you know of any please share. Appreciate it! 2021/11/12 17:24 Hello there! Do you know if they make any plugins

Hello there! Do you know if they make any plugins to assist with Search Engine
Optimization? I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good success.
If you know of any please share. Appreciate it!

# Hello there! Do you know if they make any plugins to assist with Search Engine Optimization? I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good success. If you know of any please share. Appreciate it! 2021/11/12 17:24 Hello there! Do you know if they make any plugins

Hello there! Do you know if they make any plugins to assist with Search Engine
Optimization? I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good success.
If you know of any please share. Appreciate it!

# Hello there! Do you know if they make any plugins to assist with Search Engine Optimization? I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good success. If you know of any please share. Appreciate it! 2021/11/12 17:25 Hello there! Do you know if they make any plugins

Hello there! Do you know if they make any plugins to assist with Search Engine
Optimization? I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good success.
If you know of any please share. Appreciate it!

# bimatoprost generic best price https://bimatoprostrx.com
bimatoprost buy
2021/12/13 16:10 Hksfnjkh

bimatoprost generic best price https://bimatoprostrx.com
bimatoprost buy

# finasteride prostate https://finasteridemen.com/
2022/05/11 23:52 Finasteride

finasteride prostate https://finasteridemen.com/

# doxycycline without a prescription https://antibiotic.best/ 2022/10/08 8:54 Antibiotic

doxycycline without a prescription https://antibiotic.best/

# Comprehensive side effect and adverse reaction information. Get warning information here.
https://edonlinefast.com
Comprehensive side effect and adverse reaction information. Get warning information here. 2023/02/16 17:50 EdPills

Comprehensive side effect and adverse reaction information. Get warning information here.
https://edonlinefast.com
Comprehensive side effect and adverse reaction information. Get warning information here.

# earch our drug database. Everything what you want to know about pills.
https://edonlinefast.com
earch our drug database. Comprehensive side effect and adverse reaction information. 2023/02/17 23:08 EdPills

earch our drug database. Everything what you want to know about pills.
https://edonlinefast.com
earch our drug database. Comprehensive side effect and adverse reaction information.

# Read now. Everything information about medication.
https://canadianfast.com/
Everything information about medication. Everything what you want to know about pills. 2023/02/20 0:24 CanadaBest

Read now. Everything information about medication.
https://canadianfast.com/
Everything information about medication. Everything what you want to know about pills.

# doors2.txt;1 2023/03/14 17:02 aPAeucJAjcQiHFVa

doors2.txt;1

# prednisone 25mg from canada https://prednisonepills.pro/# - prednisone 60 mg tablet 2023/06/05 1:36 Prednisone

prednisone 25mg from canada https://prednisonepills.pro/# - prednisone 60 mg tablet

# Paxlovid buy online https://paxlovid.bid/ paxlovid 2023/10/26 0:38 Paxlovid

Paxlovid buy online https://paxlovid.bid/ paxlovid

タイトル  
名前  
Url
コメント