我正在使用MVVM模式.在我的ViewModel中,我有一个公共的ObservableCollection:
public ObservableCollection<SettingsTemplateHistoryItemViewModel> HistoryItemCollection;
public SettingsTemplateViewModel()
{
this.HistoryItemCollection = new ObservableCollection<SettingsTemplateHistoryItemViewModel>();
}
Run Code Online (Sandbox Code Playgroud)
在我的视图中,我有一个ItemsControl,其ItemsSource属性绑定到ViewModel中的ObservableCollection.
<ItemsControl ItemsSource="{Binding HistoryItemCollection}"/>
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
BindingExpression path error: 'HistoryItemCollection' property not found on 'object' ''SettingsTemplateViewModel' (HashCode=48413709)'. BindingExpression:Path=HistoryItemCollection; DataItem='SettingsTemplateViewModel' (HashCode=48413709); target element is 'ItemsControl' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
Run Code Online (Sandbox Code Playgroud)
我很困惑.我100%确定该属性存在于View的DataContext(即ViewModel)中.我已将属性名称复制并粘贴到View中,因此绑定路径必须正确.View和ViewModel通过隐式/类型化DataTemplates连接起来.我错过了什么?
就像绑定错误所说,您的itemscontrol的datacontext不包含名为HistoryItemCollection的公共属性.在运行时检查datacontext的简单方法是使用Snoop
编辑:您必须使用属性而不是字段.
public ObservableCollection<SettingsTemplateHistoryItemViewModel> HistoryItemCollection {get;set;}
Run Code Online (Sandbox Code Playgroud)