为什么 Silverlight View 不抛出空异常?
Why does Silverlight View not throw a null exception?
给定一个具有以下绑定的 Silverlight 视图:
<TextBox Width="200" Text="{Binding Customer.FirstName, Mode=TwoWay}"/>
后面的代码如下:
CustomerClass Customer {get; set;}
这不会抛出 NullReferenceException
但是下面的
String FirstName
{
get { return Customer.FirstName; }
}
当我尝试绑定到 FirstName
而不是 Customer.FirstName
时,为什么会这样?如何更正? (除了直接绑定到 Customer.FirstName
或初始化 CustomerClass
对象)
编辑:解决可能的重复问题。我认为绑定在视图第一次初始化时仍然试图获取引用,不是这样吗?如果是这样,那么我可以看到获取参考和仅在查看时绑定之间的区别
XAML 绑定本身不会抛出 NullReferenceException
,但它们也不会捕获 属性 getter 抛出的异常。在一些像 WPF 这样的 "flavors," 中,有像 FallbackValue
和 TargetNullValue
这样的扩展绑定属性。 (我不确定 Silverlight 支持多少。)
当绑定失败时,会写入跟踪警告信息,但不会抛出异常。
在第一种情况下,属性 getter 被评估并且 returning null
。
在第二种情况下,属性 getter 被评估但由于异常不能 return 绑定系统的值。
要更正它,只需检查 getter 中的 null
和 return 如果是,则为默认值:
string FirstName
{
get { return Customer == null ? string.Empty : Customer.FirstName; }
}
I thought that the binding still tried to get a reference when the view is first initialized, is this not the case?
绑定过程旨在处理空值,并将检查给定的初始目标 reference,如果为空则不会尝试任何操作。 记住绑定只是反射命名 path/location 的过程,而不是值的实际提取。
当绑定发现它试图反射的 位置 为空时,它就停在那里。
但是当它被赋予 FirstName
的绑定时,绑定的 location reference 是非常有效的。答对了!然后,当最终操作 在绑定 去提取一个值时, getter
被调用,最终抛出异常,因为 Customer
或 FirstName
是空。
how could this be corrected?
考虑将 TargetNullValue, which is an alternate binding to use when null. Or directly providing a FallbackValue 添加到绑定中,以便在绑定为空时使用。
或者将 GUI 设计为不依赖可能为空的对象的子属性。
给定一个具有以下绑定的 Silverlight 视图:
<TextBox Width="200" Text="{Binding Customer.FirstName, Mode=TwoWay}"/>
后面的代码如下:
CustomerClass Customer {get; set;}
这不会抛出 NullReferenceException
但是下面的
String FirstName
{
get { return Customer.FirstName; }
}
当我尝试绑定到 FirstName
而不是 Customer.FirstName
时,为什么会这样?如何更正? (除了直接绑定到 Customer.FirstName
或初始化 CustomerClass
对象)
编辑:解决可能的重复问题。我认为绑定在视图第一次初始化时仍然试图获取引用,不是这样吗?如果是这样,那么我可以看到获取参考和仅在查看时绑定之间的区别
XAML 绑定本身不会抛出 NullReferenceException
,但它们也不会捕获 属性 getter 抛出的异常。在一些像 WPF 这样的 "flavors," 中,有像 FallbackValue
和 TargetNullValue
这样的扩展绑定属性。 (我不确定 Silverlight 支持多少。)
当绑定失败时,会写入跟踪警告信息,但不会抛出异常。
在第一种情况下,属性 getter 被评估并且 returning null
。
在第二种情况下,属性 getter 被评估但由于异常不能 return 绑定系统的值。
要更正它,只需检查 getter 中的 null
和 return 如果是,则为默认值:
string FirstName
{
get { return Customer == null ? string.Empty : Customer.FirstName; }
}
I thought that the binding still tried to get a reference when the view is first initialized, is this not the case?
绑定过程旨在处理空值,并将检查给定的初始目标 reference,如果为空则不会尝试任何操作。 记住绑定只是反射命名 path/location 的过程,而不是值的实际提取。
当绑定发现它试图反射的 位置 为空时,它就停在那里。
但是当它被赋予 FirstName
的绑定时,绑定的 location reference 是非常有效的。答对了!然后,当最终操作 在绑定 去提取一个值时, getter
被调用,最终抛出异常,因为 Customer
或 FirstName
是空。
how could this be corrected?
考虑将 TargetNullValue, which is an alternate binding to use when null. Or directly providing a FallbackValue 添加到绑定中,以便在绑定为空时使用。
或者将 GUI 设计为不依赖可能为空的对象的子属性。