假设我的屏幕上有一个部分,其中编辑了"当前记录"..所以我的视图模型有一个包含所有当前编辑属性的类,例如:
class Record { 
    public string Notes { get { return "Foo"; } set { _notes = value; Notify("Notes"); }
}
我们将此类添加到视图模型中:
class AdjustsmentViewModel {
    public Record CurrentRecord { get { return new Record(); }}
}
如何在我的视图中绑定到CurrentRecord的Notes属性?我试过这个:
<TextBox Text="{Binding CurrentRecord.Notes, Mode=TwoWay}" VerticalScrollBarVisibility="Auto" TextWrapping="WrapWithOverflow" AcceptsReturn="True"  />
但这不起作用.我也试过设置周围StackPanel的DataContext:
<StackPanel DataContext="{Binding CurrentRecord}">
之后,我尝试了我的TextBox {Binding Notes}和{Binding Path = Notes},但这些似乎都不起作用.
也许上面真的应该工作,我在其他地方搞乱一些事情?
更新
这发生在用户控件中.此用户控件具有单独的视图模型,从其父窗口开始.
this.DataContext = UnityUtil.Resolve<AdjustmentsViewModel>();
此外,我看到一个绑定错误:"对象"''MainViewModel'上找不到'Notes'属性
该视图模型在主窗口中设置.
为了验证我有正确的ViewModel绑定,我只是直接在viewmodel上添加了这个属性:
public string Notes2 { get { return "Bar"; } } 
和视图中的相应文本块:
<TextBlock Text="{Binding Path=Notes2}" />
这按预期工作.
巨大的成功
感谢Ryan,我能够找到问题所在.它不是属性本身,而是CurrentRecord的设置方式.在我的setter中,我调用了INotifyPropertyChange处理程序,但其中包含了该属性的旧名称.所以视图没有得到CurrentRecord通知,所以我猜Notes通知是不够的..
总之,这种表示法是正确的:{Binding Path = CurrentRecord.Notes}
以上应该有效,{Binding Path = CurrentRecord.Notes}是对的.你能检查一下你的datacontext是否设置为你的viewmodel?
还要检查您的viewmodel是否实现了INotifyPropertyChanged.
编辑:我刚刚创建了一个示例项目来重新创建它.无需实现INotifyPropertyChanged,只需将datacontext设置为VM即可.
| 归档时间: | 
 | 
| 查看次数: | 7754 次 | 
| 最近记录: |