我有一个ListBox,我需要将其ControlTemplate设置为Virtualizing WrapPanel,它是一个扩展VirtualizingPanel的类,使用如下所示的样式:
<Style TargetType="{x:Type ListBox}" x:Key="PhotoListBoxStyle">
<Setter Property="Foreground" Value="White" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBox}" >
<s:VirtualizingVerticalWrapPanel>
</s:VirtualizingVerticalWrapPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Run Code Online (Sandbox Code Playgroud)
现在,在下面虚拟化WrapPanel的私有方法中,我尝试访问this.ItemContainerGenerator,但我得到null值,任何想法是什么问题?
private void RealizeFirstItem()
{
IItemContainerGenerator generator = this.ItemContainerGenerator;
GeneratorPosition pos = generator.GeneratorPositionFromIndex(0);
using (generator.StartAt(pos, GeneratorDirection.Forward))
{
UIElement element = generator.GenerateNext() as UIElement;
generator.PrepareItemContainer(element);
this.AddInternalChild(element);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 7
我想我遇到了类似的问题,这有助于:
var necessaryChidrenTouch = this.Children;
IItemContainerGenerator generator = this.ItemContainerGenerator;
Run Code Online (Sandbox Code Playgroud)
...出于某种原因,您必须"触摸"子集合才能使ItemContainerGenerator正确初始化.