我有一个用户控件,我的用户控件有DependencyProperty
作为参考类型
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
属性有一个空引用异常,但是我在构造函数中从它创建了一个新实例。
答案 0 :(得分: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(组合框,选择item = null?)
希望这可以帮助你...