首页 > 解决方案 > 单击一个子元素时如何禁用滚动

问题描述

我们建立了一个“菜单”,这个菜单由几个项目集合组成:

我们有一个 ScrollViewer,其中包含每个集合的控件:

<ScrollViewer VerticalScrollBarVisibility="Auto" CanContentScroll="False"  >
    <ItemsControl ItemsSource="{Binding Collections}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <local:MenuCollections SlotCollection="{Binding}" SelectedItem="{Binding Path=DataContext.SelectedItem, RelativeSource={RelativeSource AncestorType=ItemsControl}, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Vertical" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
</ScrollViewer>

在这个控件中,我们有一个标题和一个包含所有子项的列表框:

<StackPanel Name="RootContainer" Orientation="Vertical">
    <StackPanel.DataContext>
        <local:DeviceMenuSlotCollectionViewModel/>
    </StackPanel.DataContext>
    <Label Content="{Binding SlotCollection.Name}" Margin="5,7,0,10"/>
    <ListBox ItemsSource="{Binding Path=CollectionView, UpdateSourceTrigger=PropertyChanged}" HorizontalContentAlignment="Stretch" Padding="0" BorderThickness="0" SelectedValue="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType={x:Type local:DeviceMenuSlotCollection}}, Mode=TwoWay}">
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="Padding" Value="0"/>
            </Style>
        </ListBox.ItemContainerStyle>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <local:DeviceMenuItem Slot="{Binding}" SelectedItem="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=SelectedItem}" Margin="0"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Vertical" />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
    </ListBox>
</StackPanel>

当我单击一个 DeviceMenuItem 时,它会被正确选择,一切正常。但是,如果我滚动了一下,隐藏“Item A 1”和“Item A 2”,然后单击“Item A 3”,ScrollViewer 会滚动显示“Item A 1”和“Item A 2”。

我们不想要这个,这个滚动太多了。如何禁用此滚动更改?

标签: wpfxamlscrollviewer

解决方案


当 a 中的部分可见元素获得ScrollViewer焦点时,会引发 RequestBringIntoView 事件,请求父级ScrollViewer将整个元素范围滚动到视图中。然而,这通常不是所期望的行为,因为它会导致这种“抽搐”滚动。最简单的预防方法是在事件冒泡到 parent 之前对其进行处理ScrollViewer

 <ScrollViewer>
        <ItemsControl x:Name="ic" RequestBringIntoView="OnItemsControlRequestBringIntoView">
            . . .
        </ItemsControl>
    </ScrollViewer>

private void OnListBoxRequestBringIntoView(object sender, RequestBringIntoViewEventArgs e)
{
   e.Handled = true;
}

推荐阅读