我有一个用于 WPF 和 MVVM 的 ViewModel 类:
public class ViewModel {
/* Other members here... */
public ReadOnlyObservableCollection<BackplaneViewModel> Backplanes {
get { return _Backplanes; }
}
public BackplaneViewModel CurrentBackplane {
get {
var cb = _CurrentBackplane ?? (_CurrentBackplane = Backplanes.First());
return cb;
}
set {
if (_CurrentBackplane == value) return;
_CurrentBackplane = value;
RaisePropertyChanged("CurrentBackplane");
}
}
}
集合在_Backplanes
构造函数中创建和填充,并且永远不会更改。
我有一个控件,它使用 this 的一个实例ViewModel
作为它的DataContext
. 用户可以选择CurrentBackplane
带有 a 的ComboBox
:
<ComboBox ItemsSource="{Binding Backplanes}"
SelectedItem="{Binding CurrentBackplane}"
DisplayMemberPath="BackplaneIndex" />
CurrentBackplane
也可以在代码中更改。
get
我在of上放了一个断点CurrentBackplane
。cb
变量不是null。但是,在WPF
请求它的值之后,我立即在输出窗口中得到以下信息:
System.Windows.Data Information: 40 : BindingExpression path error: 'BackplaneIndex' property not found for 'object' because data item is null. This could happen because the data provider has not produced any data yet. BindingExpression:Path=BackplaneIndex; DataItem=null; target element is 'ComboBox' (Name=''); target property is 'NoTarget' (type 'Object')
System.Windows.Data Information: 19 : BindingExpression cannot retrieve value due to missing information. BindingExpression:Path=BackplaneIndex; DataItem=null; target element is 'ComboBox' (Name=''); target property is 'NoTarget' (type 'Object')
System.Windows.Data Information: 20 : BindingExpression cannot retrieve value from null data item. This could happen when binding is detached or when binding to a Nullable type that has no value. BindingExpression:Path=BackplaneIndex; DataItem=null; target element is 'ComboBox' (Name=''); target property is 'NoTarget' (type 'Object')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=BackplaneIndex; DataItem=null; target element is 'ComboBox' (Name=''); target property is 'NoTarget' (type 'Object')
为什么WPF
告诉我数据项为空?
我不确定我做错了什么。该程序实际上运行良好,但我正在尝试追踪我认为可能与此问题有关的内存泄漏。