2012-02-27 4 views
0

DependencyPropertiesについて不思議に思っていただけです。DependencyProperty PropertyChangedCallbackとコードを直接セッターに配置する

通常、DependencyPropertyが変更された後にコードを実行するときに、この種のコーディング標準が表示されます。

public int SomeProperty 
    { 
     get { return (int)GetValue(SomePropertyProperty); } 
     set 
     { 
      SetValue(SomePropertyProperty, value); 

      //Execute code in here 
     } 
    } 

    public static readonly DependencyProperty SomePropertyProperty = 
     DependencyProperty.Register("SomeProperty", typeof(int), typeof(MainWindow), new UIPropertyMetadata(0)); 

が、これは悪い習慣を考えられている -

public int SomeProperty 
    { 
     get { return (int)GetValue(SomePropertyProperty); } 
     set { SetValue(SomePropertyProperty, value); } 
    } 

    public static readonly DependencyProperty SomePropertyProperty = 
     DependencyProperty.Register("SomeProperty", typeof(int), typeof(MainWindow), new UIPropertyMetadata(new DependencyPropertyChangedEventHandler(OnSomePropertyChanged))); 

    private static void OnSomePropertyChanged(object obj, DependencyPropertyChangedEventArgs e) 
    { 
     //Some logic in here 
    } 

しかし、私は、実装のこの種を見たことがないとは思いませんか?

ありがとうございます!

答えて

3

これは悪いことではありませんが、実際には正しく動作しません。 XAMLの依存関係プロパティにバインドするとき、SetValueメソッドはsetterではなく直接呼び出されます。基本的には、そのコードが実行されることを保証することはできません。

出典:ここにサイドノートのhttp://www.switchonthecode.com/tutorials/wpf-tutorial-introduction-to-dependency-properties

少し - これまでGetValueメソッドとSetValueをプロパティラッパーの内部で呼び出す が、何も入れないでください。これは ラッパーを介してプロパティを設定するか、SetValue呼び出しを介してプロパティを設定するかどうかを決して知ることができないため、 です。 プロパティラッパーに余分なロジックを配置したくないためです。たとえば、 にXAMLの依存関係プロパティの値を設定すると、プロパティラッパー は使用されません。プロパティラッパーに入れたものは をバイパスして直接SetValue呼び出しにヒットします。

+0

プロパティをバインドすると、それは 'SetBinding'です... –

関連する問題