ScrollIntoView方法不适用于我的水平ListBox

时间:2014-09-29 22:34:28

标签: c# xaml silverlight windows-phone-8

我创建了一个水平ListBox,用绑定数据填充它并设置其默认项目,它在屏幕的“外部”。之后,我调用了ScrollIntoView方法,但没有任何反应。我做错了什么?

我的XAML的相关部分(我认为问题出在这里):

<ListBox.ItemsPanel>
    <ItemsPanelTemplate>
        <VirtualizingStackPanel Orientation="Horizontal" />
    </ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.Template>
    <ControlTemplate TargetType="ItemsControl">
        <ScrollViewer HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Disabled">
            <ItemsPresenter x:Name="itemsPresenter" />
        </ScrollViewer>
    </ControlTemplate>
</ListBox.Template>

和C#代码:

reservationsListBox.SelectedIndex = 40;
reservationsListBox.ScrollIntoView(reservationsListBox.Items[reservationsListBox.SelectedIndex]);

1 个答案:

答案 0 :(得分:0)

在你的ControlTemplate中,ScrollViewer需要x:Name =“ScrollViewer”。

<ListBox.Template>
    <ControlTemplate TargetType="ItemsControl">
        <ScrollViewer x:Name="ScrollViewer" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Disabled">
            <ItemsPresenter x:Name="itemsPresenter" />
        </ScrollViewer>
    </ControlTemplate>
</ListBox.Template>

否则ScrollIntoView函数找不到要滚动的查看器。