2011-12-11 8 views
1

私は私のユーザーコントロールが PersonのようなrefrenceタイプとしてDependencyPropertyを持つユーザーコントロールがあります:私はMyPersonプロパティにnull参照の例外を持ってChangePerson()を呼び出すが、私はそれからの新しいインスタンスを作成するときに依存型プロパティを参照型として定義するにはどうすればよいですか?

public static readonly DependencyProperty MyPesonProperty = 
    DependencyProperty.Register("Peson", typeof(Person), typeof(MyUserControl), 
     new FrameworkPropertyMetadata 
     { 
      BindsTwoWayByDefault = true 

     }); 

public Person MyPeson 
{ 
    get { return (Person)GetValue(MyPesonProperty); } 
    set { 
      SetValue(MyPesonProperty , value); 
     } 
} 

public MyUserControl() 
{ 
     InitializeComponent(); 
     MyPeson= new Person(); 
} 

public ChangePerson() 
{ 
     MyPeson.FistName="B"; 
     MyPeson.LastName="BB"; 
} 

をコンストラクタで

+1

あなたのコードは正常に見える...(コンボボックス、選択した項目= nullを?)これはあなたを助け

希望これはnullに設定バインディング、MyPersonへの結合を確認してください。 MyPesonプロパティをどこかで(おそらくデータバインディングで)ヌルに設定しないことは確かですか? – nemesv

+0

ええ、そうだよ... –

+0

nullを小道具にバインドしている場合、簡単な答えはChangePerson()内でヌルチェックを行うことです。 –

答えて

1

あなたのコードに問題はありません。できます。

public partial class Window8 : Window 
{ 
    public static readonly DependencyProperty MyPersonProperty = 
    DependencyProperty.Register("MyPerson", 
           typeof(Person), 
           typeof(Window8), 
           new FrameworkPropertyMetadata(null, new PropertyChangedCallback(MyPersonPropertyChangedCallback)) {BindsTwoWayByDefault = true}); 

    private static void MyPersonPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { 
    if (e.NewValue == null) { 
     // ups, why is this null??? 
    } 
    } 

    public Person MyPerson { 
    get { return (Person)this.GetValue(MyPersonProperty); } 
    set { this.SetValue(MyPersonProperty, value); } 
    } 

    public Window8() { 
    this.InitializeComponent(); 
    this.MyPerson = new Person(); 
    } 

    private void Button_Click(object sender, RoutedEventArgs e) { 
    // do something.... 
    this.MyPerson.FistName = "B"; 
    this.MyPerson.LastName = "BB"; 
    } 
} 

今、あなたは何ができますか?

デバッグを試して、ブレークポイントをMyPersonPropertyChangedCallbackに設定して、どうなるか見てみましょう。

あなたはおそらく

関連する問題