Wpf MVVM Binding ListView с данными, отличными от DataContext - PullRequest
0 голосов
/ 22 марта 2020

Я пытаюсь создать usercontrol, который показывает 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;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...