2011-12-11 56 views
1

我有我的用戶控件具有DependencyProperty爲refrence型像 Person用戶控件:如何將依賴項屬性定義爲引用類型?

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"; 
} 

當我打電話ChangePerson()我有一個空引用例外MyPerson財產,但我從它創建一個新的實例在構造函數中。

+1

您的代碼看起來不錯。你確定你不把'MyPeson'屬性設置爲null(可能與數據綁定)? – 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,看看會發生什麼。

檢查您有約束力MyPerson,也許是綁定將其設置爲空(組合框,選擇的項目= NULL?)

希望這可以幫助你......

相關問題