C# insert 方法 inside derived collection - 绑定停止工作,但外部工作
C# insert method inside derived collection - binding stops working, but outside works
首先抱歉可能不是最好的标题,我不知道如何更好地表达它。这也意味着我可能会错过类似的已回答问题。请随意为其他人推荐一个更好的标题:)
我的问题很简单。 我导出了 collection 限制在我的 object,它看起来像这样:
public sealed class TrajectoryCollection<T> : ObservableCollection<T> where T : TrajectoryPoint
{
public string FileName { get; set; }
public void AddPointUnder(T selectedPoint)
{
var newPoint = (TrajectoryPoint)selectedPoint.Clone();
var nextIndex = Items.IndexOf(selectedPoint) + 1;
newPoint.SetPosition(PositionBetween(selectedPoint, Items.ElementAt(nextIndex)));
Items.Insert(nextIndex, (T)newPoint);
RecalculatePointIndexes();
}
public void RemovePoint(T item)
{
Remove(item);
RecalculatePointIndexes();
}
private void RecalculatePointIndexes()
{
for (int i = 0; i < Count; i++)
{
Items.ElementAt(i).Number = i + 1;
}
}
private Point3D PositionBetween(Point3D first, Point3D second)
{
return new Point3D(Math.Round((first.X + second.X) / 2, 3), Math.Round((first.Y + second.Y) / 2, 3), Math.Round((first.Z + second.Z) / 2, 3));
}
}
在我的 ViewModel 中我有这个(轨迹绑定到 ListView itemsource):
public TrajectoryCollection<TrajectoryPoint> Trajectory
{
get => _trajectory;
set => SetProperty(ref _trajectory, value);
}
public TrajectoryPoint SelectedPoint
{
get => _selectedPoint;
set => SetProperty(ref _selectedPoint, value);
}
private void RemovePointFromTrajectoryExecute()
{
var selectedIndex = Trajectory.IndexOf(SelectedPoint);
Trajectory.RemovePoint(SelectedPoint);
SelectedPoint = Trajectory.ElementAt(selectedIndex);
RefreshViewport();
}
private void AddPointToTrajectoryExecute()
{
var selectedIndex = Trajectory.IndexOf(SelectedPoint);
Trajectory.AddPointUnder(SelectedPoint);
SelectedPoint = Trajectory.ElementAt(selectedIndex + 1);
RefreshViewport();
}
private void RefreshViewport()
{
RaisePropertyChanged("Trajectory");
RaisePropertyChanged("SelectedPoint");
}
删除点有效,但添加无效。添加一点后,它被添加到 collection (我已经验证过),但 ListView 不会显示它 - 它的行为就像它跳过添加的行(因此它显示例如项目 1,2,3 ,5,6...),当我向下滚动时,它抛出一个异常
System.InvalidOperationException: 'An ItemsControl is inconsistent with its items source.
但是。当我将该代码从派生 collection 移动到我的 ViewModel 时,它看起来像这样:
private void AddPointToTrajectoryExecute()
{
var newPoint = (TrajectoryPointModel)SelectedPoint.Clone();
var nextIndex = Trajectory.IndexOf(SelectedPoint) + 1;
//new Point3D is PositionBetween
newPoint.SetPosition(new Point3D(Math.Round((SelectedPoint.X + Trajectory.ElementAt(nextIndex).X) / 2, 3), Math.Round((SelectedPoint.Y + Trajectory.ElementAt(nextIndex).Y) / 2, 3), Math.Round((SelectedPoint.Z + Trajectory.ElementAt(nextIndex).Z) / 2, 3)));
Trajectory.Insert(nextIndex, newPoint);
RefreshViewport();
}
它按预期工作,没有任何例外!
谁能解释一下为什么会这样?我该怎么做才能使我的 Collection.AddPointUnder() 方法正常工作?
提前致谢!
我认为问题如下:在您的添加中,您是在基础 Items
集合中插入。而删除直接发生在 ObservableCollection
上。在 ObservableCollection
上使用 Insert
或 InsertItem
,它应该可以很好地更新您的视图。这是因为 ObservableCollection
的 Items
集合不可观察。