ScrollIntoView方法没有';我无法处理水平列表框

本文关键字:处理 水平 列表 方法 ScrollIntoView | 更新日期: 2023-09-27 18:24:58

我制作了一个水平的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]);

ScrollIntoView方法没有';我无法处理水平列表框

在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函数无法找到要滚动的查看器。