gpt4 book ai didi

.net - WPF说,数据项不为空时为空

转载 作者:行者123 更新时间:2023-12-03 10:49:10 27 4
gpt4 key购买 nike

我有一个与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集合是在构造函数中创建和填充的,并且永不更改。

我有一个控件使用此 ViewModel的实例作为其 DataContext。用户可以使用 CurrentBackplane选择 ComboBox:
<ComboBox ItemsSource="{Binding Backplanes}"
SelectedItem="{Binding CurrentBackplane}"
DisplayMemberPath="BackplaneIndex" />
CurrentBackplane也可以在代码中更改。

我在 getCurrentBackplane上设置了一个断点。 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告诉我数据项为空?

我不确定自己在做什么错。该程序实际上运行良好,但是我试图找出可能与该问题有关的内存泄漏。

最佳答案

在构造函数中将集合的值设置为第一个值并将 setter/getter 代码更改为仅返回_CurrentBackplane之后,是否尝试过设置_CurrentBackplane?

_CurrentBackplane = Backplanes.First();  


public BackplaneViewModel CurrentBackplane {  
get {
return _CurrentBackplane;
}
set { _CurrentBackplane = value; }
}

关于.net - WPF说,数据项不为空时为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11748233/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com