wpf - 单击一个子元素时如何禁用滚动
问题描述
我们建立了一个“菜单”,这个菜单由几个项目集合组成:
- A类物品
- 项目 A 1
- 项目 A 2
- 项目 A 3
- B类物品
- 项目 B 1
- 项目 B 2
- 项目 B 3
- 项目 B 4
- 项目 B 5
- C类物品
- 项目 C 1
- 项目 C 2
我们有一个 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”。
我们不想要这个,这个滚动太多了。如何禁用此滚动更改?
解决方案
当 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;
}
推荐阅读
- sql - 伪码要求
- google-cloud-run - 429 无明显原因的速率超出响应
- scala - 如何在 scala/sbt 中安装 scodec 库?
- python - Python中嵌套while循环的问题
- modelica - 在 Modelica 模型中离散 PDE 的时间导数项
- javascript - 加载延迟的问题
- javascript - 无法使用 jquery DataTable 在 html 表中显示 Json 数据
- swift - 移动时在设备屏幕中心附加球体
- javascript - 我可以仅在 Tabulator.js 中加载时扩展一个节点吗?
- r - 是否可以在exams2nops 中使用解决方案模板?