Wpf ICollectionView Binding item cannot resolve property of type object

前端 未结 3 1394
孤城傲影
孤城傲影 2021-02-19 15:00

I have bound a GridView with an ICollectionView in the XAML designer the properties are not known because the entity in the CollectionView

3条回答
  •  温柔的废话
    2021-02-19 15:38

    Neither d:DataContext="{d:DesignInstance Type=lcl:ViewModel}"> nor GenericCollectionView works directly for a DataGrid with a CollectionViewSource.

        

    We can't set "d:DataContext"; because, we often need to bind multiple properties to our viewmodel.

    The CollectionViewSource creates new ListCollectionView which is runtime instantiated each time you set the Source property. Since setting the Source property is the only reasonable way to refresh a range of rows, we can't keep a GenericCollectionView around.

    My solution is perhaps perfectly obvious, but I dumped the CollectionViewSource. By making creating a property

    private ObservableCollection _rowDataStoreAsList;
    public GenericCollectionView TypedCollectionView
    {
      get => _typedCollectionView;
      set { _typedCollectionView = value; OnPropertyChanged();}
    }
    
    public void FullRefresh()
    {
        var listData = _model.FetchListingGridRows(onlyListingId: -1);
        _rowDataStoreAsList = new ObservableCollection(listData);
        var oldView = TypedCollectionView;
        var saveSortDescriptions = oldView.SortDescriptions.ToArray();
        var saveFilter = oldView.Filter;
        TypedCollectionView = new GenericCollectionView(new ListCollectionView(_rowDataStoreAsList));
        var newView = TypedCollectionView;
        foreach (var sortDescription in saveSortDescriptions)
        {
            newView.SortDescriptions.Add(new SortDescription()
            {
                Direction = sortDescription.Direction,
                PropertyName = sortDescription.PropertyName
            });
        }
        newView.Filter = saveFilter;
    }
    internal void EditItem(object arg)
    {
        var view = TypedCollectionView;
        var saveCurrentPosition = view.CurrentPosition;
        var originalRow = view.TypedCurrentItem;
        if (originalRow == null)
            return;
        var listingId = originalRow.ListingId;
        var rawListIndex = _rowDataStoreAsList.IndexOf(originalRow);
        // ... ShowDialog ... DialogResult ...
        var lstData = _model.FetchListingGridRows(listingId);
        _rowDataStoreAsList[rawListIndex] = lstData[0];
        view.MoveCurrentToPosition(saveCurrentPosition);
        view.Refresh();
    }
    

    After adding public T TypedCurrentItem => (T)collectionView.CurrentItem; To the GenericCollectionView provided by Maxence.

提交回复
热议问题