【问题标题】:WPF MVVM binding errorWPF MVVM 绑定错误
【发布时间】:2013-01-31 07:35:17
【问题描述】:

我正在使用 MVVM 模式。在我的 ViewModel 中,我有一个公共的 ObservableCollection:

public ObservableCollection<SettingsTemplateHistoryItemViewModel> HistoryItemCollection;

public SettingsTemplateViewModel()
    {
        this.HistoryItemCollection = new ObservableCollection<SettingsTemplateHistoryItemViewModel>();
    }

在我的视图中,我有一个 ItemsControl,它的 ItemsSource 属性绑定到 ViewModel 中的 ObservableCollection。

<ItemsControl ItemsSource="{Binding HistoryItemCollection}"/>

我收到以下错误:

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')

我很困惑。我 100% 确定该属性存在于 View 的 DataContext(即 ViewModel)中。我已将属性名称复制并粘贴到视图中,因此绑定路径必须正确。 View 和 ViewModel 通过隐式/类型化的 DataTemplates 连接起来。我错过了什么?

【问题讨论】:

  • 使用属性而不是字段。

标签: wpf mvvm binding


【解决方案1】:

就像绑定错误所说,您的 itemscontrol 的数据上下文不包含名为 HistoryItemCollection 的公共属性。在运行时检查数据上下文的一种简单方法是使用Snoop

编辑:您必须使用属性而不是字段。

public ObservableCollection<SettingsTemplateHistoryItemViewModel> HistoryItemCollection {get;set;}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 2021-03-01
    • 2017-05-01
    • 2015-05-24
    • 1970-01-01
    相关资源
    最近更新 更多