c# - Wpf MVVM将ListView绑定到DataContext以外的数据
问题描述
我正在尝试创建一个显示 MainList 和 OtherList 的用户控件,该控件显示来自不同模型的只读数据。
我已经像这样设置了我的 Datacontext:
xmlns:viewModel="clr-namespace:MyAssembly.ViewModel"
<UserControl.DataContext>
<viewModel:MainListViewModel/>
</UserControl.DataContext>
并像这样填写我的 mainList:
<Grid>
<ListView Margin="10" ItemsSource="{Binding MainList}">
<ListView.View>
<GridView>
<GridViewColumn Header="Col1" Width="Auto" DisplayMemberBinding="{Binding Col1}" />
<GridViewColumn Header="Col2" Width="Auto" DisplayMemberBinding="{Binding Col2}" />
<GridViewColumn Header="Col3" Width="Auto" DisplayMemberBinding="{Binding Col3}" />
</GridView>
</ListView.View>
</ListView>
</Grid>
<ListView Margin="10" ItemsSource="{Binding OtherList}">
<ListView.View>
<GridView>
<GridViewColumn Header="OtherCol1" Width="Auto" DisplayMemberBinding="{Binding OtherCol1}" />
<GridViewColumn Header="OtherCol2" Width="Auto" DisplayMemberBinding="{Binding OtherCol2}" />
<GridViewColumn Header="OtherCol3" Width="Auto" DisplayMemberBinding="{Binding OtherCol3}" />
</GridView>
</ListView.View>
</ListView>
MainListViewModel.cs 看起来像这样并实现了INotifyPropertyChanged:
private Datalayer=_datalayer;
public MainListViewModel()
{
_datalayer= new Datalayer("connection");
MainList = new ObservableCollection<MainListModel>(_dataLayer.GetMainList().Select(x => new MainlistModel(x)));
OtherList = new ObservableCollection<OtherListModel>(_dataLayer.GetOtherList().Select(x => new OtherlistModel(x)));
}
private ObservableCollection<MainListModel> _mainList;
public ObservableCollection<MainListModel> MainList
{
get => _mainList;
set
{
if (_mainList == value)
return;
_mainList = value;
//below is inherited from the class that implements the INotifyPropertyChanged
RaisePropertyChanged();
}
}
private ObservableCollection<OtherListModel> _otherList;
public ObservableCollection<OtherListModel> OtherList
{
get => _otherList;
set
{
if (_otherList == value)
return;
_otherList = value;
//below is inherited from the class that implements the INotifyPropertyChanged
RaisePropertyChanged();
}
}
现在,上面的代码按我的 MainList 的预期工作,我得到了正确的数据来填充我的 OtherList,但我找不到从 OtherListModel 绑定每个字段的方法。
此外,当我加载这个 UserControl 时,我得到了这个异常:
InvalidOperationException:使用 ItemsSource 时操作无效。改为使用 ItemsControl.ItemsSource 访问和修改元素。
当调试器到达这一点时会发生这种情况:
public ObservableCollection<OtherListModel> OtherList
{
get => _otherList;
解决方案
推荐阅读
- java - jmsTemplate 在 Spring Boot 中不会自动初始化
- url - 在 Drupal 8 中使用 Twig 检索图像资产绝对 URL
- c# - 通过 ngnix 在 Ubuntu VPS 上部署 .Net Core 和 Angular 作为 SPA
- javascript - Microsoft Graph 令牌将在 1 天后过期
- spf - 跟踪启用 DMARC 发送的电子邮件
- php - 如何通过网络问卷发送电子邮件?
- django - 让用户使用 Django 在服务器中下载大文件的最佳方式
- python - 尝试获取滚动相关性时的 NAN 值
- ios - 格式化日期后,角度日期管道在 iphone/ios 上显示 NaN
- dart - Dart 使用引用隔离 SendPort 和 ReceivePort 问题