かずきのBlog

C#やJavaやRubyとメモ書き

目次

Blog 利用状況

ニュース

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

書庫

日記カテゴリ

[C#][WPF]イベントじゃけん その2

その1:http://blogs.wankuma.com/kazuki/archive/2008/02/21/124157.aspx

その2と名乗りつつ前の続きではないという罠。
WPFのイベントはルーティングイベントとかいってWindowsFormsのイベントとはちょっと違う動きをする。

WindowsFormsのイベントと同じだとちょっと困る例を示してみようと思う。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace WpfEventIntro
{
    public class MyApplication : Application
    {
        public MyApplication()
        {
            Startup += (sender, e) =>
                {
                    HelloEventWindow window = new HelloEventWindow();
                    window.Show();
                };
        }

        [STAThread]
        static void Main(string[] args)
        {
            new MyApplication().Run();
        }
    }

    public class HelloEventWindow : Window
    {
        public HelloEventWindow()
        {
            Init();
        }

        private void Init()
        {
            // 画面組み立て
            var stackPanel = new StackPanel();
            Content = stackPanel;

            var btn1 = new Button();
            var current = btn1;
            for (int i = 0; i < 10; i++)
            {
                var btn2 = new Button();
                current.Content = btn2;
                current = btn2;
            }

            stackPanel.Children.Add(btn1);
        }
    }
}

とりあえずこんなコード。HelloEventWindowのInitメソッドで画面の組み立てをやってる。forループを回してボタンの中にボタンを10個入れ子にしてみた。
実行すると、下のような普通はお目にかかれないような雰囲気のものが出来上がる。
image

これの一番下のボタンにクリックイベントをこさえる。

        private void Init()
        {
            // 画面組み立て
            var stackPanel = new StackPanel();
            Content = stackPanel;

            var btn1 = new Button();
            // イベントですよ
            btn1.Click += (sender, e) => MessageBox.Show("押されたんじゃ~");

            var current = btn1;
            for (int i = 0; i < 10; i++)
            {
                var btn2 = new Button();
                current.Content = btn2;
                current = btn2;
            }

            stackPanel.Children.Add(btn1);
        }

たったこれだけで、11個あるボタンのどれを押しても下のようにメッセージボックスが出る。
image

WPFのイベントは、イベントが起きると親へ親へとイベントを伝播していく。
因みに、イベントが親へ親へ伝播されるまえに、Preview~という名前のイベントも起きたりする。こっちは親から子へ伝播する。

というわけで、ボタンの中にあるボタンを押下しても、クリックイベントは親へ親へ渡され、いずれボタンクリックイベントが登録されてるbtn1へたどり着くって寸法です。
こういう動きをすることで、いろいろな要素が合成されて作られたものでも、今までと同じ感覚でイベントを記述することができるようになってるという寸法。

こんな動きをするイベントだから、WindowsFormsと同じようにコントロール作ってイベント作ってとかやっても同じように動かない。
WPFのイベントの仕組みのお作法に従う必要がある。

お作法ってのは、DependencyPropertyを定義するときとほとんど同じでいけます。
ためしにHogeというイベントを上記のウィンドウに追加する場合は下のようになります。

        public static readonly RoutedEvent HogeEvent = EventManager.RegisterRoutedEvent(
            "Hoge", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(HelloEventWindow));

EventManagerに登録ってやればOK。
んで、これだけじゃあんまりなので既存のC#で作ったクラスのイベントみたいに扱えるようなコードを書き足します。

        public static readonly RoutedEvent HogeEvent = EventManager.RegisterRoutedEvent(
            "Hoge", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(HelloEventWindow));
        public event RoutedEventHandler Hoge
        {
            add { AddHandler(HogeEvent, value); }
            remove { RemoveHandler(HogeEvent, value); }
        }

これでイベントHoge完成!通常のC#のようなイベントの登録方法でもいけるし、AddHandlerメソッドを使ってWindowとか、まったく関係ない人に処理をお願いしてもOKだろう。

投稿日時 : 2008年2月21日 23:27

Feedback

# Christian Louboutin Booties 2012/12/08 4:46 http://mychristianlouboutinonline.webs.com/

of course like your web-site however you need to take a look at the spelling on several of your posts. A number of them are rife with spelling issues and I in finding it very bothersome to tell the truth however I will definitely come back again.

# longchamp pas cher 2012/12/14 22:31 http://www.soldesacslongchamp.info/category/sac-lo

I won't know... there's something tacky on the subject of owning Ferrari branded stuff like this.. unless additionally you own a genuine Ferrari.

# sacs longchamp 2012/12/15 15:29 http://www.saclongchampachete.info/category/longch

I work with earbuds overseas because of the portability, even though I favor over any ear.

# sacs longchamp 2012/12/16 21:04 http://www.sacslongchamp2012.info/longchamps-darsh

I really don't know... there's a thing tacky pertaining to owning Ferrari branded stuff like this.. unless moreover, you may own a proper Ferrari.

# Sac Michael Kors Shoulder 2012/12/17 6:59 http://www.sacmichaelkors.net

Those are a lot more awesome. Looks for example klipsch is really made to work alongside iProducts? I want android types!

# 安いトリーバーチ 2012/12/17 20:15 http://www.torybruchjp.info/category/トリーバーチ

If many people sound superior I'd utterly wear these at your home.

# burberry uk sale 2012/12/18 20:21 http://www.burberryoutlet2012.info/category/burber

The only individuals would appear good wearing these fugly things can be Ferrari hole crew while in the pits:D

# burberry en ligne 2012/12/18 21:31 http://sacburberrysoldesfr.webnode.fr/blog

Go throughout these mature items and just look for your personal that tickle ones own fancy.

# burberry bags 2012/12/19 13:23 http://burberryoutlet2013sale.webeden.co.uk/#/abou

we re-watched the lord of the particular Rings trilogy, the Godfather trilogy, and pertaining to twenty various movies that people loved along with hadn¡¯t watched in any while.

# burberry scarf 2012/12/21 2:15 http://burberryoutlet2013sale.webeden.co.uk

If your current photostream features photos which usually - when good or perhaps not - triggered a new spirited comments¡ä thread.

# michael kors soldes 2012/12/22 17:14 http://sacmichaelkorssoldes.monwebeden.fr/#/photos

Its chance are consequently fantastic plus working form so easy.

# www.tt6262.com 2013/03/04 5:08 http://tt6262.com/

Friends that you shop for by creates will be bought from most people. www.tt6262.com http://tt6262.com/

# casquette chicago bulls 2013/03/14 19:48 http://www.a77.fr/

Want a particular accounting system in the valued at, matter neighbors. casquette chicago bulls http://www.a77.fr/

# casquette obey 2013/03/17 7:02 http://www.b44.fr/

Don‘tonne endeavor so desperately, the best quality activities are produced as soon as you smallest be expecting these. casquette obey http://www.b44.fr/

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

For those who may you want to keep magic from the an opponent, say to the following by way of the an acquaintance. destockchine http://d77.fr/

# usine23 2013/03/25 5:15 http://e55.fr/

You should never speak of your main delight to significantly less fortunate enough when compared to you. usine23 http://e55.fr/

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

In order for an accountancy from your deserving of, count number your folks. destockchine http://c99.fr/

# 3suisses 2013/04/07 1:24 http://ruenee.com/

Although individual doesn‘l love you a task long for them that will,doesn‘l imply that which they get into‘l love you boost they've. 3suisses http://ruenee.com/

# rueducommerce 2013/04/07 7:30 http://ruezee.com/

Cheer rrs really a parfum that people dump to do with some others with out enjoying a variety of lowers to do with your lifestyle. rueducommerce http://ruezee.com/

# brandalley 2013/04/07 12:05 http://rueree.com/

Delight is a essence you won't pullulate with others lacking applying for a limited declines with you and your family. brandalley http://rueree.com/

# coachoutletcoupon44.com 2013/04/07 14:51 http://www.coachoutletcoupon44.com/

Companion that you choose and pick up together with shows is purchased from anyone. coachoutletcoupon44.com http://www.coachoutletcoupon44.com/

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

I'm sure take a look at on account of what you are, yet unfortunately on account of what people I'm certainly photographs am along with you. chaussea http://ruemee.com/

# Hello mates, how is all, and what you desire to say on the topic of this post, in my view its truly awesome in support of me. 2021/07/12 22:15 Hello mates, how is all, and what you desire to sa

Hello mates, how is all, and what you desire to
say on the topic of this post, in my view its truly awesome in support
of me.

# I've read some just right stuff here. Definitely value bookmarking for revisiting. I surprise how a lot attempt you put to create this kind of excellent informative web site. 2021/07/18 9:41 I've read some just right stuff here. Definitely v

I've read some just right stuff here. Definitely value bookmarking for
revisiting. I surprise how a lot attempt you put to create
this kind of excellent informative web site.

# It's amazing to pay a visit this site and reading the views of all friends on the topic of this post, while I am also eager of getting familiarity. 2021/09/03 2:49 It's amazing to pay a visit this site and reading

It's amazing to pay a visit this site and reading the views of all friends on the topic of this post, while I am also eager of getting familiarity.

# It's amazing to pay a visit this site and reading the views of all friends on the topic of this post, while I am also eager of getting familiarity. 2021/09/03 2:50 It's amazing to pay a visit this site and reading

It's amazing to pay a visit this site and reading the views of all friends on the topic of this post, while I am also eager of getting familiarity.

# It's amazing to pay a visit this site and reading the views of all friends on the topic of this post, while I am also eager of getting familiarity. 2021/09/03 2:51 It's amazing to pay a visit this site and reading

It's amazing to pay a visit this site and reading the views of all friends on the topic of this post, while I am also eager of getting familiarity.

# It's amazing to pay a visit this site and reading the views of all friends on the topic of this post, while I am also eager of getting familiarity. 2021/09/03 2:52 It's amazing to pay a visit this site and reading

It's amazing to pay a visit this site and reading the views of all friends on the topic of this post, while I am also eager of getting familiarity.

# Thankfulness to my father who told me on the topic of this webpage, this website is in fact awesome. quest bars http://bit.ly/3jZgEA2 quest bars 2021/09/12 1:56 Thankfulness to my father who told me on the topic

Thankfulness to my father who told me on the topic of this webpage, this website
is in fact awesome. quest bars http://bit.ly/3jZgEA2 quest bars

# Good day! I know this is somewhat off topic but I was wondering which blog platform are you using for this site? I'm getting tired of Wordpress because I've had issues with hackers and I'm looking at alternatives for another platform. I would be fantas 2021/09/13 19:01 Good day! I know this is somewhat off topic but I

Good day! I know this is somewhat off topic but I was wondering which
blog platform are you using for this site? I'm getting tired of Wordpress because I've had issues with hackers and I'm looking at alternatives for another platform.
I would be fantastic if you could point me in the direction of
a good platform. scoliosis surgery https://coub.com/stories/962966-scoliosis-surgery scoliosis surgery

# Amazing! This blog looks just like my old one! It's on a entirely different topic but it has pretty much the same page layout and design. Superb choice of colors! https://parttimejobshiredin30minutes.wildapricot.org/ part time jobs hired in 30 minutes 2021/10/22 20:58 Amazing! This blog looks just like my old one! It'

Amazing! This blog looks just like my old one! It's
on a entirely different topic but it has pretty much the same page layout
and design. Superb choice of colors! https://parttimejobshiredin30minutes.wildapricot.org/ part time jobs hired in 30 minutes

# Amazing! This blog looks just like my old one! It's on a entirely different topic but it has pretty much the same page layout and design. Superb choice of colors! https://parttimejobshiredin30minutes.wildapricot.org/ part time jobs hired in 30 minutes 2021/10/22 20:59 Amazing! This blog looks just like my old one! It'

Amazing! This blog looks just like my old one! It's
on a entirely different topic but it has pretty much the same page layout
and design. Superb choice of colors! https://parttimejobshiredin30minutes.wildapricot.org/ part time jobs hired in 30 minutes

# What i don't understood is in truth how you're not actually much more neatly-liked than you might be now. You are very intelligent. You understand thus significantly in the case of this matter, made me personally consider it from so many various angles. 2021/10/25 14:09 What i don't understood is in truth how you're not

What i don't understood is in truth how you're not
actually much more neatly-liked than you might be
now. You are very intelligent. You understand thus significantly in the case of this matter,
made me personally consider it from so many various angles.

Its like men and women are not interested except it's one thing to do
with Woman gaga! Your personal stuffs outstanding. At all
times care for it up!

# It's hard to find experienced people on this topic, but you seem like you know what you're talking about! Thanks 2021/11/13 11:26 It's hard to find experienced people on this topic

It's hard to find experienced people on this topic,
but you seem like you know what you're talking about! Thanks

タイトル
名前
Url
コメント