DependencyObject
依存関係プロパティが使えるようになる。
通常のプロパティをCLRプロパティと呼んだりする。
値の変化で呼ばれるメソッドを登録できる。
class ClassDepTest : DependencyObject
String型の名前hogeという依存プロパティをつくり、これが変更されたらHogePropertyChanged関数を呼ぶようにしてみる。hogeの初期値は"aaaa"にした。
public static readonly DependencyProperty hogeProperty = DependencyProperty.Register("hoge",//プロパティ名 typeof(String),//プロパティ型 typeof(ClassDepTest),//所有者型 new PropertyMetadata("aaaaa", HogePropertyChanged));
このように、デフォルト値や、プロパティが変わった時のコールバックを設定できる。
コールバック関数は適当に書いておく。
private static void HogePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { System.Diagnostics.Debug.WriteLine("プロパティ"+d+"@@"+e); String v = d.GetValue(hogeProperty) as String; System.Diagnostics.Debug.WriteLine("値 == "+v); // throw new NotImplementedException(); }
ラッパーを作っておくと.hogeでアクセスできる。
// hoge変数は結局、依存プロパティhogePropertyの値をセット、ゲットするだけ。 public String hoge { get { return (String)this.GetValue(hogeProperty); } set { this.SetValue(hogeProperty, value); } }
これでhogeの値を変えようとすると中でコールバック関数が呼ばれる。
var cTest = new ClassDepTest(); var pre = cTest.hoge; cTest.hoge = "Hi!"; var post = cTest.hoge; System.Diagnostics.Debug.WriteLine("pre "+pre+"post " + post);
出力結果
値 == Hi! pre aaaaapost Hi!