当我们在 View 和 View-Model 之间进行双向绑定时,我们实现了 INotifyPropertyChanged 接口,该接口具有以下事件:
// Summary:
// Occurs when a property value changes.
event PropertyChangedEventHandler PropertyChanged;
但是我可以在不实现 INotifyPropertyChanged 的情况下做同样的事情吗?
If you can't implement INotifyPropertyChanged
(INPC) (or don't have the source to what you want to bind to) then you should wrap whatever it is you want to bind to in your View Model and the View Model would implement INPC for the binding and have to to get/set data to, presumably, that other class.
你当然可以。当视图模型更改时,您只需放松更新视图的简单方法。现在有办法克服这一点。
DataContext
,这样所有绑定都会再次被评估,但这非常昂贵。但显然这些都是非常奇怪的解决方法。还值得一提的是,绑定到未实现 INotifyPropertyChanged 的对象通常较慢。
如果您想避免INotifyPropertyChanged
显式实现,可以使用 PostSharp 之类的代码编织工具。然后,实现INotifyPropertyChanged
变得如此简单
[NotifyPropertyChanged]
public class Shape
{
public double X { get; set; }
public double Y { get; set; }
}
您可以在此处找到更多详细信息:http: //www.sharpcrafters.com/solutions/notifypropertychanged#。
我会说不。您必须以任何方式实现 INotifyPropertyChanged,否则与 twoway 绑定将不起作用。