我正在尝试使用WPF ListBox创建一个图形控件。 我创建了自己的Canvas,它派生自VirtualizingPanel,并且我自己处理项目的实现和虚拟化。
然后将列表框的项面板设置为我的自定义虚拟化画布。
我遇到的问题发生在以下场景中:
- 首先创建ListBox Item A。
- 在画布上,在Item A的右侧创建ListBox Item B。
- 首先将ListBox Item A虚拟化(通过将其滑动出视图)。
- 第二个被虚拟化的是ListBox Item B(同样是通过将其滑动出视图)。
- 将ListBox Item A和B带回视图中(即实现它们)
- 使用Snoop,我检测到ListBox现在有3个项,其中一个是位于ListBox Item B直接下方的“DisconnectedItem”。
是什么导致创建这个“DisconnectedItem”?如果我首先虚拟化B,然后是A,就不会创建此项。我的理论是,在ListBox中虚拟化先于其他项的项会导致子项断开连接。
使用具有数百个节点的图形时,问题更加明显,因为当我四处移动时,我最终会得到数百个已断开连接的项。
以下是Canvas代码的一部分:
/// <summary>
/// Arranges and virtualizes child element positionned explicitly.
/// </summary>
public class VirtualizingCanvas : VirtualizingPanel
{
(...)
protected override Size MeasureOverride(Size constraint)
{
ItemsControl itemsOwner = ItemsControl.GetItemsOwner(this);
// For some reason you have to "touch" the children collection in
// order for the ItemContainerGenerator to initialize properly.
var necessaryChidrenTouch = Children;
IItemContainerGenerator generator = ItemContainerGenerator;
IDisposable generationAction = null;
int index = 0;
Rect visibilityRect = new Rect(
-HorizontalOffset / ZoomFactor,
-VerticalOffset / ZoomFactor,
ActualWidth / ZoomFactor,
ActualHeight / ZoomFactor);
// Loop thru the list of items and generate their container
// if they are included in the current visible view.
foreach (object item in itemsOwner.Items)
{
var virtualizedItem = item as IVirtualizingCanvasItem;
if (virtualizedItem == null ||
visibilityRect.IntersectsWith(GetBounds(virtualizedItem)))
{
if (generationAction == null)
{
GeneratorPosition startPosition =
generator.GeneratorPositionFromIndex(index);
generationAction = generator.StartAt(startPosition,
GeneratorDirection.Forward, true);
}
GenerateItem(index);
}
else
{
GeneratorPosition itemPosition =
generator.GeneratorPositionFromIndex(index);
if (itemPosition.Index != -1 && itemPosition.Offset == 0)
{
RemoveInternalChildRange(index, 1);
generator.Remove(itemPosition, 1);
}
// The generator needs to be "reseted" when we skip some items
// in the sequence...
if (generationAction != null)
{
generationAction.Dispose();
generationAction = null;
}
}
++index;
}
if (generationAction != null)
{
generationAction.Dispose();
}
return default(Size);
}
(...)
private void GenerateItem(int index)
{
bool newlyRealized;
var element =
ItemContainerGenerator.GenerateNext(out newlyRealized) as UIElement;
if (newlyRealized)
{
if (index >= InternalChildren.Count)
{
AddInternalChild(element);
}
else
{
InsertInternalChild(index, element);
}
ItemContainerGenerator.PrepareItemContainer(element);
element.RenderTransform = _scaleTransform;
}
element.Measure(new Size(double.PositiveInfinity,
double.PositiveInfinity));
}