【问题标题】:Databinding in windows forms on an object graph with possible null properties?具有可能为空属性的对象图上的 Windows 窗体中的数据绑定?
【发布时间】:2009-01-15 13:50:49
【问题描述】:

如果我有这样的对象图:

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

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

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

并使用以下方法将数据绑定到控件:

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

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

Company c2 = new Company();

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

【问题讨论】:

    标签: winforms data-binding


    【解决方案1】:

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

    【讨论】:

    • 这仍然是推荐的方法吗?多年来,我一直在试图弄清楚如何最好地解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-23
    • 2011-09-30
    • 2019-06-29
    • 2017-09-25
    • 1970-01-01
    • 2018-09-21
    • 2012-02-12
    相关资源
    最近更新 更多