我认为您需要调用BringIntoView
项目容器,而不是 ItemsControl 本身:
var container = DocumentElements.ItemContainerGenerator.ContainerFromItem(model) as FrameworkElement;
if (container != null)
container.BringIntoView();
编辑:实际上这不起作用,因为此时项目容器尚未生成......您可能可以StatusChanged
处理ItemContainerGenerator
. 我尝试了以下代码:
public static class ItemsControlExtensions
{
public static void BringItemIntoView(this ItemsControl itemsControl, object item)
{
var generator = itemsControl.ItemContainerGenerator;
if (!TryBringContainerIntoView(generator, item))
{
EventHandler handler = null;
handler = (sender, e) =>
{
switch (generator.Status)
{
case GeneratorStatus.ContainersGenerated:
TryBringContainerIntoView(generator, item);
break;
case GeneratorStatus.Error:
generator.StatusChanged -= handler;
break;
case GeneratorStatus.GeneratingContainers:
return;
case GeneratorStatus.NotStarted:
return;
default:
break;
}
};
generator.StatusChanged += handler;
}
}
private static bool TryBringContainerIntoView(ItemContainerGenerator generator, object item)
{
var container = generator.ContainerFromItem(item) as FrameworkElement;
if (container != null)
{
container.BringIntoView();
return true;
}
return false;
}
}
但是它也不起作用......由于某种原因,ContainerFromItem
在状态更改为 后仍然返回 null ContainersGenerated
,我不知道为什么:S
编辑:好的,我现在明白了......这是因为虚拟化:容器仅在需要显示时生成,因此不会为隐藏项目生成容器。如果您为 ItemsControl ( ) 关闭虚拟化VirtualizingStackPanel.IsVirtualizing="False"
,则上述解决方案可以正常工作。