2014年1月26日日曜日

仮想化してるのに表示が遅い

WPF で ListBox を横方向にスクロールするために下記のようなコードを書いた。
<ListBox
    HorizontalAlignment="Stretch"
    ItemsSource="{Binding Hoge}"
    VerticalAlignment="Stretch"
    VirtualizingPanel.IsVirtualizing="True"
    >
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>
このコードで実行したところ、描画が非常に遅くなった。
仮想化が効いていない?と悩み調べたところ、
http://stackoverflow.com/questions/2143655/wpf-list-boxes-and-virtualization
らしい。

VirtualizingPanel のプロパティを指定しているのに、VirtualizingPanel とは無縁の StackPanel を使っていれば仮想化されないのは当然だ。
<ListBox
    HorizontalAlignment="Stretch"
    ItemsSource="{Binding Hoge}"
    VerticalAlignment="Stretch"
    VirtualizingPanel.IsVirtualizing="True"
    >
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>
これで仮想化されるようになった。