无需 INotifyPropertyChanged 即可双向数据绑定到 POCO
当数据源对象的属性不在其 setter 中引发 PropertyChanged
事件时,Silverlight 中的双向数据绑定如何工作?
例如,在代码示例中,我看到了与 System.Windows.Point
结构实例的数据绑定,该结构未实现 INotifyPropertyChanged
并且是可变的嗯>。如果有人直接在 Point 中设置 X
和 Y
属性,而不是用新实例替换该对象,会发生什么(或应该发生)?
How does two-way databinding work in Silverlight when the data source object's properties don't raise PropertyChanged
events in their setters?
For example, in code samples, I've seen databinding to instances of the System.Windows.Point
struct, which does not implement INotifyPropertyChanged
and is mutable. What happens (or should happen) if someone sets the X
and Y
properties directly in the Point, rather than replacing the object with a new instance?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Point 是一个结构体,因此即使 Point 是可变的,从属性调用中获取的 Point 与存储在底层字段中的 Point 并不相同;这是一个副本。因此,如果您改变副本,基础字段将保持不变。不需要属性更改通知,因为属性的值实际上并未更改。只有当类实际上直接改变其私有字段中的 Point 时才会出现问题。当结构体发生变化时,由类实现者决定是否不执行此操作或手动调用 PropertyChanged 通知。
这是可变结构危险的原因之一。它们不能通过属性进行突变,但该类的客户端可能会错误地认为它们可以。
Point is a struct, so even though Point is mutable, the Point you get from the property call is not the same as the Point stored in the underlying field; it's a copy. As such, if you mutate the copy, the underlying field remains the same. There is no need for a property changed notification, because the value of the property has not actually changed. There would only be a problem if the class actually mutated the Point in its private field directly. It's up to the class implementer to either not do this or manually invoke the PropertyChanged notification when the struct is mutated.
This is one reason why mutable structs are dangerous. They cannot be mutated through a property, but clients of the class may incorrectly assume that they can be.
用户界面不更新。这里没有魔法。没有抛出事件意味着 UI 将错过更新。
The UI does not update. There is no magic here. No event thrown means the UI will miss the update.