Windows窗体中的数据绑定是否具有可能的null属性?

时间:2022-06-09 20:54:24

If I have an object graph like this:

如果我有这样的对象图:

class Company {
  public Address MainAddress {...}
}

class Address {
  public string City { ... }
}

Company c = new Company();
c.MainAddress = new Address();
c.MainAddress.City = "Stockholm";

and databind to a control using:

和数据绑定到控件使用:

textBox1.DataBinding.Add( "Text", c, "MainAddress.City" );

Everything is fine, but If I bind to:

一切都很好,但如果我绑定到:

Company c2 = new Company();

c2 using the same syntax it crashes since the MainAddress property is null. I wonder if there is a custom Binding class that can set up listeners for all the possible paths here and bind to the actual object dynamically when/if I sometime later in the application set the MainAddress property.

c2使用相同的语法崩溃,因为MainAddress属性为null。我想知道是否有一个自定义Binding类可以为这里的所有可能路径设置监听器,并在/稍后在应用程序中设置MainAddress属性时动态绑定到实际对象。

1 个解决方案

#1


You should change the getter of the property MainAddress to do this null check, and return an "empty MainAddress"

您应该更改属性MainAddress的getter以执行此null检查,并返回“空MainAddress”

#1


You should change the getter of the property MainAddress to do this null check, and return an "empty MainAddress"

您应该更改属性MainAddress的getter以执行此null检查,并返回“空MainAddress”