WPF ItemsControl 取消选中item项,滚动条自动跑到该item顶部的问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF ItemsControl 取消选中item项,滚动条自动跑到该item顶部的问题相关的知识,希望对你有一定的参考价值。
项目中ItemsControl 自定义了DataTemplate,代码如下:
<ScrollViewer x:Name="PaperScrollCiewer" Margin="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Background="#ccc" ScrollChanged="PaperScrollCiewer_ScrollChanged" > <ItemsControl x:Name="MainItemsControl"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <StackPanel/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <Grid> <Grid.RowDefinitions> <RowDefinition Height="10"></RowDefinition> <RowDefinition Height="10*"></RowDefinition> </Grid.RowDefinitions> <InkCanvas Grid.Row="1" Background="{Binding ImgPath,Converter={StaticResource BitmapSourceConvert}}" Strokes="{Binding Strokes}" Width="{Binding Width}" Height="{Binding Height}"> <InkCanvas.DefaultDrawingAttributes> <DrawingAttributes Color="#FFFB1818" FitToCurve="False" Height="3" IgnorePressure="False" IsHighlighter="False" StylusTip="Ellipse" StylusTipTransform="Identity" Width="3"/> </InkCanvas.DefaultDrawingAttributes> </InkCanvas> </Grid> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </ScrollViewer>
其中InkCanvas是用来添加墨迹的,功能就是想实现加载很多个画布,每个画布能单独的绘制墨迹。运行时候发现第一次点击某一个画布,滚动条就自动调整到该item的顶部去了,猜想是触发了SelectedChange事件,默认该item选中时候需要对齐。
解决方法很简单,给ItemsControl设置属性CanContentScroll="True",完美解决。
修改后代码如下:
<ScrollViewer x:Name="PaperScrollCiewer" Margin="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Background="#ccc" ScrollChanged="PaperScrollCiewer_ScrollChanged" CanContentScroll="True">
<ItemsControl x:Name="MainItemsControl">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="10"></RowDefinition>
<RowDefinition Height="10*"></RowDefinition>
</Grid.RowDefinitions>
<InkCanvas Grid.Row="1" Background="{Binding ImgPath,Converter={StaticResource BitmapSourceConvert}}" Strokes="{Binding Strokes}" Width="{Binding Width}" Height="{Binding Height}">
<InkCanvas.DefaultDrawingAttributes>
<DrawingAttributes Color="#FFFB1818" FitToCurve="False" Height="3" IgnorePressure="False" IsHighlighter="False" StylusTip="Ellipse" StylusTipTransform="Identity" Width="3"/>
</InkCanvas.DefaultDrawingAttributes>
</InkCanvas>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
以上是关于WPF ItemsControl 取消选中item项,滚动条自动跑到该item顶部的问题的主要内容,如果未能解决你的问题,请参考以下文章
禁用WPF TreeView(或TreeViewItem)选择?