【发布时间】:2010-03-05 15:43:12
【问题描述】:
假设有这种 CLR 对象:
public class Foo
{
...
public Bar { get; private set; }
}
public class Bar: INotifyPropertyChanged
{
public string Baz { get {...} set {...} }
}
现在我有一个窗口,DataContext 绑定到 Foo 的一个实例。在这个窗口中我这样做:
<TextBox Text={Binding Bar.Baz} />
因为 Foo 没有实现 INotifyPropertyChanged,我将在这里得到一个众所周知的 WPF 内存泄漏。有两种解决方案:
- 在 上实现 INotifyPropertyChange
- Foo 使用 OneTime 绑定
我不喜欢 1),所以假设我们想使用 OneTime 绑定。 但是我只需要 OneTime 绑定来访问 Bar,而我需要 TwoWay 绑定来访问 Baz:
<TextBox DataContext="{Binding Bar, Mode=OneTime}" Text={Binding Baz, Mode=TwoWay} />
到目前为止一切都很好,但是如果现在需要将 TextBox 中的一些其他属性绑定到 Foo 的属性,事情就会变得复杂,因为 DataContext 不再是 Foo 实例了。
那么问题来了:有没有办法指定将 OneTime 绑定到父属性并将 TwoWay 绑定到子属性的 Bindig(在 XAML 或代码中)?
【问题讨论】: