Reputation: 3763
I have a user control that my user control has a DependencyProperty
as a refrence type like
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";
}
when I call ChangePerson()
I have a null reference exception for MyPerson
property but I create a new instance from it in the constructor.
Upvotes: 1
Views: 754
Reputation: 14611
i have no problems with your code. it works.
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";
}
}
now, what can you do?
try debug and set a breakpoint to MyPersonPropertyChangedCallback
and look what happens.
check you binding to MyPerson, perhaps the binding set this to null (combobox, selected item = null?)
hope this helps you...
Upvotes: 1