かずきのBlog

C#やJavaやRubyとメモ書き

目次

Blog 利用状況

ニュース

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

書庫

日記カテゴリ

[C#][WPF]コマンドですよ その10 「Command + Binding」

その9:http://blogs.wankuma.com/kazuki/archive/2008/03/24/129257.aspx

ということで、データバインディングと共にコマンドを使ってみようと思う。
唐突かもしれないけど、ICommandSourceを実装するクラスには大体CommandParameterとかいうプロパティが定義されてる。
それは、多くのクラスで依存プロパティとして定義されている!ということはバインドすることが出来る。List系のバインドと組み合わせると、選択してる要素に対して何かをやるとかいったことがすっきり書けそうな気がする。
ということで早速実験。

まずは、Personクラスと今回使うコマンドを定義する。

using System.Windows.Input;

namespace WpfCommand10
{
    public static class SampleCommands
    {
        public static readonly RoutedUICommand Detail = new RoutedUICommand(
            "詳細表示", "Detail", typeof(SampleCommands));
    }

    public class Person
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
    }
}

そして、Window1.xaml.csのDataContextに、Personの配列をつっこんでおく。

        public Window1()
        {
            InitializeComponent();
            DataContext = new[] { 
                new Person { ID = 0, Name = "田中 太郎", Age = 54, Address = "東京都のどっか1" },
                new Person { ID = 1, Name = "2中 2郎", Age = 10, Address = "東京都のどっか2" },
                new Person { ID = 2, Name = "3中 3郎", Age = 3, Address = "東京都のどっか3" },
                new Person { ID = 3, Name = "4中 4郎", Age = 1, Address = "東京都のどっか4" },
            }; 
        }

 

この勢いで画面もさくっと作る!!
画面的には詳細ボタンの乗ったToolBarが上部にあって、下部にGrid形式のListViewがいる。
ListViewにはIDと名前と年齢を表示しておいて、詳細ボタンを押したときに、メッセージボックスに住所まで含めた情報を表示する。

<Window x:Class="WpfCommand10.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:WpfCommand10="clr-namespace:WpfCommand10"
    Title="Window1" Height="300" Width="300">
    <Window.CommandBindings>
        <!-- 詳細表示コマンドをバインド -->
        <CommandBinding 
            Command="{x:Static WpfCommand10:SampleCommands.Detail}" 
            Executed="DetailCommandBinding_Executed" 
            CanExecute="DetailCommandBinding_CanExecute" />
    </Window.CommandBindings>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <ToolBarTray>
            <ToolBar>
                <Button Content="詳細" 
                        Command="{x:Static WpfCommand10:SampleCommands.Detail}" 
                        CommandParameter="{Binding Path=CurrentItem}"/> <!-- CurrentItemで現在行!! -->
            </ToolBar>
        </ToolBarTray>
        <ListView Grid.Row="1" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}" />
                    <GridViewColumn Header="名前" DisplayMemberBinding="{Binding Name}" />
                    <GridViewColumn Header="年齢" DisplayMemberBinding="{Binding Age}" />
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>

 

さくっとのつもりが結構時間かかってしまった。
リストをListViewにバインドするのは楽勝だったけど、ボタンのCommandParameterに現在選択されているオブジェクトを指定する方法がわからなかった。
結局のところ、このときのBindingのSourceはICollectionViewなのでCurrentItemプロパティをPathに指定してやればよかった。
ふぅ。勉強になった。

後は、CanExecuteとExecutedイベントを書いて完成。

using System.Windows;
using System.Windows.Input;

namespace WpfCommand10
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            DataContext = new[] { 
                new Person { ID = 0, Name = "田中 太郎", Age = 54, Address = "東京都のどっか1" },
                new Person { ID = 1, Name = "2中 2郎", Age = 10, Address = "東京都のどっか2" },
                new Person { ID = 2, Name = "3中 3郎", Age = 3, Address = "東京都のどっか3" },
                new Person { ID = 3, Name = "4中 4郎", Age = 1, Address = "東京都のどっか4" },
            }; 
        }

        private void DetailCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var p = e.Parameter as Person;
            if (p != null)
            {
                MessageBox.Show(string.Format("ID:{0}, Name:{1}, Age:{2}, Address:{3}", p.ID, p.Name, p.Age, p.Address));
            }
        }

        private void DetailCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = e.Parameter != null;
        }
    }
}

CanExecuteは、パラメータに値が入ってるかどうかをチェックする。
Executedは、パラメータがPersonだったらID Name Age Addressを文字列にしてメッセージボックスに表示している。

実行すると下のようになる。

起動直後
image

適当な行を選んで詳細をクリック
image image

ということで、バインドとコマンドを組み合わせればマスター詳細系のときにすっきりできそうな気がした。

以上!

投稿日時 : 2008年3月26日 23:38

Feedback

# re: [C#][WPF]コマンドですよ その10 「Command + Binding」 2008/03/27 8:58 R・田中一郎

なんで太郎なのか、小一時間くらい問い詰めたいですw

# re: [C#][WPF]コマンドですよ その10 「Command + Binding」 2008/03/28 19:39 かずき

一郎にすると…Rさんの年齢がばれちゃう!?

# バーバリー コート レディース 2012/11/06 23:50 http://burberry.suppa.jp/

お世話になります。とても良い記事ですね。

# Christian Louboutin 2012 2012/12/07 17:18 http://mychristianlouboutinonline.webs.com/

I really enjoy reading through on this site, it has got wonderful content . "Do what you fear, and the death of fear is certain." by Anthony Robbins.

# エルメス時計 2012/12/14 22:51 http://www.hermespairs.info/category/エルメス時計

Our pool has to be fed with the help of those photopages that you just consider valued at becoming an area of the "Best Thought Collection".

# soldes longchamp 2012/12/15 15:53 http://www.soldesacslongchamp.info/category/kate-m

The fashion don't crease flat as well as Philips doesn't supplies a travel pouch while in the package.

# foulard burberry 2012/12/16 4:20 http://www.sacburberryecharpe.fr/category/burberry

keep in the good do the job!

# longchamp le pliage 2012/12/16 21:42 http://www.longchampbagoutlet.info/category/longch

I genuinely like em. It's unlike you use these out walking on town many people.

# burberry coat 2012/12/17 21:00 http://www.burberrycanadaoutlet.info/category/burb

I definitely like em. It's unlike you be dressed in these out walking around town people today.

# soldesacslongchamp.info 2012/12/17 21:07 http://www.soldesacslongchamp.info

This is actually a really fantastic site blog post, im delighted I found it.

# isabel marant paris soldes 2012/12/18 20:55 http://www.isabelmarant-stores.com/category/isabel

we re-watched god, the father of that Rings trilogy, the Godfather trilogy, and concerning twenty different movies that him and i loved and hadn¡¯t watched in the while.

# michael kors 2012/12/18 22:10 http://sac-michael-kors.webnode.fr/blog/

we re-watched the lord of a Rings trilogy, the Godfather trilogy, and approximately twenty several other movies which we loved and also hadn¡¯t watched from a while.

# michael kors discount 2012/12/19 13:46 http://sac-michael-kors.webnode.fr/sur-michael-kor

I understand the too expensive garbage remark. I can't stand the glimpse, sound or even feel for the Beats.

# michael kors watche 2012/12/21 5:03 http://michaelkorswatch.webeden.co.uk

If any photostream incorporates photos of which - when good or perhaps not - triggered any spirited comments¡ä place.

# isabel marant bottes 2012/12/22 18:02 http://sneakersisabelmrant-paris.webnode.fr

Keep up the excellent job.

# destockchine 2013/01/10 22:44 http://www.destockchinefr.fr/

Well-being is usually a cologne you can't pour concerned with other ones free of receiving a some droplets concerned with your business.
destockchine http://www.destockchinefr.fr/

# , 2013/01/14 4:43 http://www.destockchine.com/

Appreciate can be the purely sane and then positive solution of staff daily life.
, http://www.destockchine.com/

# casquette supreme 2013/03/03 14:47 http://www.b66.fr/

Put on‘p make an attempt so faithfully, the best quality stuff are supplied whilst you slightest can expect these to. casquette supreme http://www.b66.fr/

# tt6262.com 2013/03/04 5:06 http://tt6262.com/

Authentic relationship foresees the needs of several other rather of laud it is always personally own. tt6262.com http://tt6262.com/

# Niketalk 2013/03/04 23:25 http://www.jordanretro10air.com/

Right affinity foresees the needs of several in preference to proclaim this is particular. Niketalk http://www.jordanretro10air.com/

# code promo la redoute 2013/03/04 23:26 http://www.k88.fr/

Right acquaintanceship foresees the needs of further rather of predicate it is usually special. code promo la redoute http://www.k88.fr/

# casquette obey 2013/03/15 5:18 http://www.b44.fr/

Put on‘big t cost your efforts in a husband/ladies,who seem to isn‘big t ready to cost the occasion done to you. casquette obey http://www.b44.fr/

# jkwpvedbymtf 2013/03/18 10:33 did you purchase this theme? zogypivldn <a hre

teutkaocyzeg

# destockchine 2013/03/25 5:13 http://c99.fr/

You should not to understand which can be comfortable to get along with. Connect with others who'll coerce one to lever tumbler your family themsleves. destockchine http://c99.fr/

# destock sport et mode 2013/04/03 7:09 http://www.ruenike.com/lunettes-c-22.html/

A good bro very likely are not companion, nevertheless companion have been any bro. destock sport et mode http://www.ruenike.com/lunettes-c-22.html/

# maillot de bain pas cher 2013/04/07 18:09 http://www.chaussuresnike2013.com/

Fancy may merely happy and in addition good enough solution associated with human appearance. maillot de bain pas cher http://www.chaussuresnike2013.com/

# Hey! This post couldn't be written any better! Reading through this post reminds me of my good old room mate! He always kept talking about this. I will forward this page to him. Fairly certain he will have a good read. Thanks for sharing! 2019/05/15 12:46 Hey! This post couldn't be written any better! Rea

Hey! This post couldn't be written any better! Reading through this post reminds me of
my good old room mate! He always kept talking about this.
I will forward this page to him. Fairly certain he will have a good read.
Thanks for sharing!

# Hey there this is somewhat of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I'm starting a blog soon but have no coding knowledge so I wanted to get guidance from someone with experience. Any 2019/07/17 11:15 Hey there this is somewhat of off topic but I was

Hey there this is somewhat of off topic but I was wanting to know if blogs
use WYSIWYG editors or if you have to manually code with HTML.

I'm starting a blog soon but have no coding knowledge so I wanted to get guidance from
someone with experience. Any help would be greatly appreciated!

# Hey there this is somewhat of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I'm starting a blog soon but have no coding knowledge so I wanted to get guidance from someone with experience. Any 2019/07/17 11:16 Hey there this is somewhat of off topic but I was

Hey there this is somewhat of off topic but I was wanting to know if blogs
use WYSIWYG editors or if you have to manually code with HTML.

I'm starting a blog soon but have no coding knowledge so I wanted to get guidance from
someone with experience. Any help would be greatly appreciated!

# Hey there this is somewhat of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I'm starting a blog soon but have no coding knowledge so I wanted to get guidance from someone with experience. Any 2019/07/17 11:17 Hey there this is somewhat of off topic but I was

Hey there this is somewhat of off topic but I was wanting to know if blogs
use WYSIWYG editors or if you have to manually code with HTML.

I'm starting a blog soon but have no coding knowledge so I wanted to get guidance from
someone with experience. Any help would be greatly appreciated!

# Hey there this is somewhat of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I'm starting a blog soon but have no coding knowledge so I wanted to get guidance from someone with experience. Any 2019/07/17 11:18 Hey there this is somewhat of off topic but I was

Hey there this is somewhat of off topic but I was wanting to know if blogs
use WYSIWYG editors or if you have to manually code with HTML.

I'm starting a blog soon but have no coding knowledge so I wanted to get guidance from
someone with experience. Any help would be greatly appreciated!

# Hmm is anyone else having problems with the images on this blog loading? I'm trying to determine if its a problem on my end or if it's the blog. Any responses would be greatly appreciated. 2019/07/21 15:12 Hmm is anyone else having problems with the images

Hmm is anyone else having problems with the images on this blog loading?
I'm trying to determine if its a problem on my end or if it's the blog.
Any responses would be greatly appreciated.

# I am sure this article has touched all the internet visitors, its really really fastidious piece of writing on building up new weblog. natalielise plenty of fish 2019/07/26 15:35 I am sure this article has touched all the interne

I am sure this article has touched all the internet visitors,
its really really fastidious piece of writing on building
up new weblog. natalielise plenty of fish

# I am sure this article has touched all the internet visitors, its really really fastidious piece of writing on building up new weblog. natalielise plenty of fish 2019/07/26 15:36 I am sure this article has touched all the interne

I am sure this article has touched all the internet visitors,
its really really fastidious piece of writing on building
up new weblog. natalielise plenty of fish

# I am sure this article has touched all the internet visitors, its really really fastidious piece of writing on building up new weblog. natalielise plenty of fish 2019/07/26 15:37 I am sure this article has touched all the interne

I am sure this article has touched all the internet visitors,
its really really fastidious piece of writing on building
up new weblog. natalielise plenty of fish

# I am sure this article has touched all the internet visitors, its really really fastidious piece of writing on building up new weblog. natalielise plenty of fish 2019/07/26 15:38 I am sure this article has touched all the interne

I am sure this article has touched all the internet visitors,
its really really fastidious piece of writing on building
up new weblog. natalielise plenty of fish

# I know this website gives quality based articles and extra material, is there any other web site which gives these data in quality? 2019/07/31 4:56 I know this website gives quality based articles a

I know this website gives quality based articles and
extra material, is there any other web site which gives
these data in quality?

# I know this website gives quality based articles and extra material, is there any other web site which gives these data in quality? 2019/07/31 4:57 I know this website gives quality based articles a

I know this website gives quality based articles and
extra material, is there any other web site which gives
these data in quality?

# I know this website gives quality based articles and extra material, is there any other web site which gives these data in quality? 2019/07/31 4:58 I know this website gives quality based articles a

I know this website gives quality based articles and
extra material, is there any other web site which gives
these data in quality?

# I know this website gives quality based articles and extra material, is there any other web site which gives these data in quality? 2019/07/31 4:59 I know this website gives quality based articles a

I know this website gives quality based articles and
extra material, is there any other web site which gives
these data in quality?

タイトル  
名前  
Url
コメント