首页 > 解决方案 > 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;

标签: c#wpfmvvm

解决方案


推荐阅读