かずきのBlog

C#やJavaやRubyとメモ書き

目次

Blog 利用状況

ニュース

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

書庫

日記カテゴリ

[C#][WPF]DependencyObjectって その4

前回:http://blogs.wankuma.com/kazuki/archive/2008/01/31/120275.aspx

間があいちゃったけど、その3では読み取り専用のDependencyPropertyを作ってみた。
今度は、添付プロパティを作ってみようと思う。

添付プロパティってのは、GridやDockPanelやValidationあたりで使われてる。
たとえば…

<Grid>
  <Button Grid.Row="1" Grid.Column="2" Content="Sample" />
</Grid>

にあるGrid.RowやGrid.Columnとかがそれにあたる。
要は、ボタンとかには本来無いプロパティを無理矢理?付け足すようなものです。
こうすることで、例みたいな本来コントロールとは関係無いレイアウトに関する情報とかを柔軟に付け加えることができる。
因みにJavaのGUIライブラリの1つSWTではLayoutDataというプロパティをコントロールが持っているという感じの作りになってたと思う。

将来的にレイアウト以外の情報を付け足そうと思うと、コントロールの基本クラスに手が入るような感じかな。
添付プロパティだと、そこらへんが割りと柔軟に拡張できるようになってる。

さて、添付プロパティですが、基本的に今までやってきた依存プロパティと大差無いです。
違いといえば、DependencyProperty.Registerで登録するかDependencyProperty.RegisterAttachedで登録するか…。
Personクラスに対していい例が思いつかなかったので、住所情報を添付プロパティでくっつけるようにしてみた。

    public class Person : DependencyObject
    {
        // 今までと同じなので省略
    }

    // 別にstatic classじゃなくてもいい。当然DependencyObjectから派生したクラスでもOK
    public static class PersonOptions
    {
        // DependencyObject.RegisterAttachedメソッドを呼ぶ以外は添付プロパティと同じ
        public static readonly DependencyProperty AddressProperty =
            DependencyProperty.RegisterAttached("Address", typeof(string), typeof(PersonOptions));
        
        // staticなSetAddressやGetAddressというメソッドが対応するメソッド
        public static void SetAddress(DependencyObject target, string value)
        {
            target.SetValue(AddressProperty, value);
        }
        public static string GetAddress(DependencyObject target)
        {
            return (string) target.GetValue(AddressProperty);
        }
    }

staticなSet~ Get~というメソッドを定義してるところ以外はあんまり変わらないと思う。
Set~ Get~というメソッドの中も、RegisterAttachedメソッドで帰ってきたDependencyProeprtyのインスタンスをキーにSetValue GetValueをしているだけ。
一緒だね。

早速これを使うサンプルをこさえてみた。

    class Program
    {
        static void Main(string[] args)
        {
            var p = new Person();
            p.Name = "田中 麻呂";
            // 添付プロパティ!
            PersonOptions.SetAddress(p, "東京都");

            Console.WriteLine(p.Name);
            // 添付プロパティ!
            Console.WriteLine(PersonOptions.GetAddress(p));
        }
    }

何も面白く無いサンプルですが…。
ちなみに、このPersonクラスのインスタンスpと同じように、名前に田中 麻呂 添付プロパティのAddressに東京都をセットされたものを作ることをXAMLで書くと下のようになります。

<p:Person xmlns:p="clr-namespace:DependencyObjectSample;assembly=DependencyObjectPropertySample" 
	Name="田中 麻呂"
	p:PersonOptions.Address="東京都"/>

これをPerson.xamlという名前で埋め込まれたリソースに設定する。それを読み込んで表示するプログラムは下のような感じ。

    class Program
    {
        static void Main(string[] args)
        {
            var p =  XamlReader.Load(
                typeof(Program).Assembly.GetManifestResourceStream(
                    "DependencyPropertySample.Person.xaml")) as Person;
            Console.WriteLine(p.Name);
            Console.WriteLine(PersonOptions.GetAddress(p));
        }
    }

どちらも実行結果は下のようになる。PropertyChangeとかCoerceValueとかで出力してるものは除外してる。

田中 麻呂様
東京都

ちなみに、昔書いた自分の記事が参考になった。
当時は添付プロパティとかよく知らなかったわ。

DependencyObjectについてはここらへんで終了かな?ネタ切れ。

投稿日時 : 2008年2月8日 0:14

Feedback

# [C#][WPF]DependencyObjectって その5 2008/02/16 14:31 かずきのBlog

[C#][WPF]DependencyObjectって その5

# re: WPF の Grid パネル 2008/03/02 9:55 R.Tanaka.Ichiro's Blog

re: WPF の Grid パネル

# sacs lancel 2012/10/19 15:34 http://www.saclancelpascher2013.com

Only a smiling visitor here to share the love (:, btw outstanding style and design. "Make the most of your regrets... . To regret deeply is to live afresh." by Henry David Thoreau.

# Christian Louboutin boots 2012/12/08 11:33 http://myclsale.webs.com/

hi!,I like your writing so much! percentage we be in contact extra approximately your post on AOL? I need an expert on this house to solve my problem. Maybe that's you! Looking ahead to look you.

# sacs longchamp soldes 2012/12/14 22:59 http://www.saclongchampachete.com/category/sacs-lo

It's ALL RIGHT. You can nevertheless be a vimeo star =)

# burberry soldes 2012/12/16 4:42 http://www.sacburberryecharpe.fr/category/burberry

I am certain that I can visit the following place once more soon.

# longchamp soldes 2012/12/16 22:10 http://www.soldesacslongchamp.info/category/sacs-l

we re-watched god of the Rings trilogy, the Godfather trilogy, and in relation to twenty other movies that any of us loved and even hadn¡¯t watched in a very while.

# longchamp outlet 2012/12/17 8:12 http://saclongchamphobo.webnode.fr

I dont know... there's a little something tacky concerning owning Ferrari branded stuff like this.. unless you furthermore may own an absolute Ferrari.

# sac burberry solde 2012/12/18 6:05 http://echarpeburberrysoldes.webnode.fr

It's O . K .. You can always be a myspace star =)

# Sacs Michael Kors 2012/12/18 22:27 http://sac-michael-kors.webnode.fr

Nobody can see you to mug you within your basement.

# burberry coats 2012/12/21 6:34 http://burberryukoutlets.wordpress.com/category/bu

I guess My business is not the only person having each of the enjoyment below!

# code promo spartoo 2013/03/05 0:47 http://www.c88.fr/

Have a passion for is actually weak from beginning, even so matures deeper as we age when it's thoroughly provided. code promo spartoo http://www.c88.fr/

# www.K88.fr 2013/03/05 0:48 http://www.k88.fr/

Put on‘capital t test drive so difficult, an excellent things go should you bare minimum anticipate it to. www.K88.fr http://www.k88.fr/

# destock chine 2013/03/05 0:50 http://www.c55.fr/

A colleague you choose to buy by working with delivers would be purchased from you will. destock chine http://www.c55.fr/

# Jordan Retro 7 Raptors 2013/03/05 0:51 http://www.jordanretro7air.com/

To the world you should be someone, and yet to a single man or woman you should be all mankind. Jordan Retro 7 Raptors http://www.jordanretro7air.com/

# flightclubny 2013/03/06 15:11 http://www.jordanretro10air.com/

Now don't make friends who definitely are contented to be with. It's the perfect time that will get 1 prize for yourself it. flightclubny http://www.jordanretro10air.com/

# casquette superman 2013/03/16 8:58 http://www.b77.fr/

Prefer may possibly be the proactive worry for ones reality in addition to increase of truley what all of us adoration. casquette superman http://www.b77.fr/

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

Put on‘w not use over-time, the most effective points go when you the very least anticipate the criminals to. destockchine http://c99.fr/

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

I adore happened simply because of who you really are, then again simply because of what individuals I'm sure when I have always been away with you. usine23 http://e55.fr/

# dorue.com 2013/04/07 14:46 http://www.dorue.com/

Found in successfulness a lot of our classmates and friends acknowledge all of; when difficulty can certainly a lot of our classmates and friends. dorue.com http://www.dorue.com/

# Good day! Do you know if they make any plugins to safeguard against hackers? I'm kinda paranoid about losing everything I've worked hard on. Any suggestions? 2019/04/18 6:58 Good day! Do you know if they make any plugins to

Good day! Do you know if they make any plugins to safeguard against hackers?
I'm kinda paranoid about losing everything I've worked hard on. Any suggestions?

# Hi, I do believe this is an excellent website. I stumbledupon it ;) I'm going to come back yet again since I book-marked it. Money and freedom is the greatest way to change, may you be rich and continue to help other people. 2019/05/03 16:59 Hi, I do believe this is an excellent website. I s

Hi, I do believe this is an excellent website. I stumbledupon it ;) I'm going to
come back yet again since I book-marked it. Money and freedom is the greatest way to change, may
you be rich and continue to help other people.

# Hello, Neat post. There's a problem together with your website in web explorer, would test this? IE nonetheless is the market leader and a big portion of other people will pass over your fantastic writing due to this problem. 2019/05/10 12:13 Hello, Neat post. There's a problem together with

Hello, Neat post. There's a problem together with your website in web explorer, would test this?
IE nonetheless is the market leader and a big portion of
other people will pass over your fantastic writing due to this problem.

# Hmm is anyone else having problems with the images on this blog loading? I'm trying to figure out if its a problem on my end or if it's the blog. Any feed-back would be greatly appreciated. 2019/05/15 15:04 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 figure out if its a problem on my end or if it's the blog.
Any feed-back would be greatly appreciated.

# Greetings! Very useful advice in this particular post! It's the little changes that make the biggest changes. Thanks for sharing! 2019/06/11 1:11 Greetings! Very useful advice in this particular p

Greetings! Very useful advice in this particular post!

It's the little changes that make the biggest changes. Thanks for
sharing!

# Hi! I could have sworn I've been to this website before but after reading through some of the post I realized it's new to me. Anyways, I'm definitely happy I found it and I'll be book-marking and checking back often! 2019/07/20 12:15 Hi! I could have sworn I've been to this website b

Hi! I could have sworn I've been to this website before but after reading
through some of the post I realized it's new to me. Anyways, I'm
definitely happy I found it and I'll be book-marking and checking back often!

タイトル
名前
Url
コメント