解决WPF程序中ListBox ItemsSource变化时不重置ScrollBar的问题
当我们改变ListBox的ItemsSource时,会发现这样一个问题:数据源变化时,虽然控件中的内容会跟着变化,但滚动条却不会重置。
举个例子:
- 将ListBox绑定到一百个字符串:listbox.ItemsSource = Enumerable.Range(0, 100).Select(i => "## " + i);。
- 将ListBox的滚动条拖到最后,使之能看到最后的"## 99",看不到最开始的"## 0"。
- 将ListBox绑定到另外一百个字符串:listbox.ItemsSource = Enumerable.Range(0, 100).Select(i => ">> " + i);。这时我们会发现:虽然数据内容会变更,但滚动条仍然在最后,能看到最后的">> 99",看不到最开始的">> 0"。
大多数情况下,这个并不是我们所期望的结果。如何解决这个问题,stackoverflow文章Reset scrollbar on ItemsSource change给了一个解决方案:找到ListBox的ScrollViewer,响应ListBox的SourceUpdated事件,滚动滚动条到顶端。
listbox.SourceUpdated += (_1, _2) => scrollView.ScrollToTop();
这种方法本身没有什么问题,但是由于ScrollViewer是视觉树的一部分,从ListBox上获取并不容易(可能会修改模板)。我后来又从Wordpress文章ListBox – Automatically scroll CurrentItem into View上找到了一个方案:响应ListBox的Items.CurrentChanged事件,通过函数ScrollIntoView实现滚动到顶端。
listbox.Items.CurrentChanged += (_1, _2) => listbox.ScrollIntoView(listbox.Items[0]);
原文本来的目的是为了实现将ListBox自动滚动到CurrentItem,也可用来解决这个问题。原文更是实现了一个附加属性,使得可以在XAML中直接使用,来非常方便。
<ListBox local:ListBoxExtenders.AutoScrollToCurrentItem="True"/>
由于众所周知的原因,Wordpress这个并不存在的网站只能从火星上访问,没有火星专线的朋友可以找方校长借,或者直接参考我下面的代码(稍微修改了点,貌似也没有什么bug)。
/// <summary>
/// This class contains a few useful extenders for the ListBox
/// </summary>
public class ListBoxExtenders : DependencyObject
{
#region Properties public static readonly DependencyProperty AutoScrollToCurrentItemProperty = DependencyProperty.RegisterAttached("AutoScrollToCurrentItem",
typeof(bool), typeof(ListBoxExtenders), new UIPropertyMetadata(default(bool), OnAutoScrollToCurrentItemChanged)); /// <summary>
/// Returns the value of the AutoScrollToCurrentItemProperty
/// </summary>
/// <param name="obj">The dependency-object whichs value should be returned</param>
/// <returns>The value of the given property</returns>
public static bool GetAutoScrollToCurrentItem(DependencyObject obj)
{
return (bool)obj.GetValue(AutoScrollToCurrentItemProperty);
} /// <summary>
/// Sets the value of the AutoScrollToCurrentItemProperty
/// </summary>
/// <param name="obj">The dependency-object whichs value should be set</param>
/// <param name="value">The value which should be assigned to the AutoScrollToCurrentItemProperty</param>
public static void SetAutoScrollToCurrentItem(DependencyObject obj, bool value)
{
obj.SetValue(AutoScrollToCurrentItemProperty, value);
} #endregion #region Events /// <summary>
/// This method will be called when the AutoScrollToCurrentItem
/// property was changed
/// </summary>
/// <param name="sender">The sender (the ListBox)</param>
/// <param name="e">Some additional information</param>
public static void OnAutoScrollToCurrentItemChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var listBox = sender as ListBox;
if ((listBox == null) || (listBox.Items == null))
return; var enable = (bool)e.NewValue;
var autoScrollToCurrentItemWorker = new EventHandler((_1, _2) => OnAutoScrollToCurrentItem(listBox, listBox.Items.CurrentPosition)); if (enable)
listBox.Items.CurrentChanged += autoScrollToCurrentItemWorker;
else
listBox.Items.CurrentChanged -= autoScrollToCurrentItemWorker;
} /// <summary>
/// This method will be called when the ListBox should
/// be scrolled to the given index
/// </summary>
/// <param name="listBox">The ListBox which should be scrolled</param>
/// <param name="index">The index of the item to which it should be scrolled</param>
public static void OnAutoScrollToCurrentItem(ListBox listBox, int index)
{
if (listBox != null && listBox.Items != null && listBox.Items.Count > index && index >= )
listBox.ScrollIntoView(listBox.Items[index]);
} #endregion
解决WPF程序中ListBox ItemsSource变化时不重置ScrollBar的问题的更多相关文章
- WPF 程序中启动和关闭外部.exe程序
当需要在WPF程序启动时,启动另一外部程序(.exe程序)时,可以按照下面的例子来: C#后台代码如下: using System; using System.Collections.Generic; ...
- 如何在WPF程序中使用ArcGIS Engine的控件
原文 http://www.gisall.com/html/47/122747-4038.html WPF(Windows Presentation Foundation)是美国微软公司推出.NET ...
- WPF程序中App.Config文件的读与写
WPF程序中的App.Config文件是我们应用程序中经常使用的一种配置文件,System.Configuration.dll文件中提供了大量的读写的配置,所以它是一种高效的程序配置方式,那么今天我就 ...
- 如何追踪 WPF 程序中当前获得键盘焦点的元素并显示出来
原文:如何追踪 WPF 程序中当前获得键盘焦点的元素并显示出来 title: "如何追踪 WPF 程序中当前获得键盘焦点的元素并显示出来" publishDate: 2019-06 ...
- 在WPF程序中使用摄像头兼谈如何使用AForge.NET控件(转)
前言: AForge.NET 是用C#写的一个关于计算机视觉和人工智能领域的框架,它包括图像处理.神经网络.遗传算法和机器学习等.在C#程序中使用摄像头,我习惯性使用AForge.NET提供的类库.本 ...
- 解决WPF的ScrollViewer在使用触摸屏时,滑到尽头窗口抖动的情况
原文:解决WPF的ScrollViewer在使用触摸屏时,滑到尽头窗口抖动的情况 wpf的ScrollViewer在触摸条件下 默认在尽头时会有一个窗口一起被拖动的FeedBack,但对用户的交互很不 ...
- 在 WPF 程序中应用 Windows 10 真?亚克力效果
原文:在 WPF 程序中应用 Windows 10 真?亚克力效果 从 Windows 10 (1803) 开始,Win32 应用也可以有 API 来实现原生的亚克力效果了.不过相比于 UWP 来说, ...
- qt之窗口换肤(一个qss的坑:当类属性发现变化时需要重置qss,使用rcc资源文件)
1.相关文章 Qt 资源系统qt的moc,uic,rcc命令的使用 2.概要 毕业两年了,一直使用的是qt界面库来开发程序,使用过vs08.10.13等开发工具,并安装了qt的插件,最近在做客户 ...
- WPF程序中的弱事件模式
在C#中,得益于强大的GC机制,使得我们开发程序变得非常简单,很多时候我们只需要管使用,而并不需要关心什么时候释放资源.但是,GC有的时并不是按照我们所期望的方式工作. 例如,我想实现一个在窗口的标题 ...
随机推荐
- php-fpm优化内存占用大
1.1 Linux的php-fpm优化心得-php-fpm进程占用内存大和不释放内存问题 LNMP架构中PHP是运行在FastCGI模式下,按照官方的说法,php-cgi会在每个请求结束的时候会回收脚 ...
- 实验楼Python项目
整理几个实验楼小项目,有免费的也有会员的,会员的可以参考他们的实验报告. 直接去实验楼这个网站,粘贴上就能搜到. 免费专区: Kmeans聚类算法评估足球比赛 Python实现3D建模工具 K-近邻算 ...
- Ubuntu下PHP+MySQL+Apache+PHPStorm的安装和配置
粘贴自:https://www.jianshu.com/p/a6a0d2a29591 1.Apache的安装: $ sudo apt-get update $ sudo apt-get install ...
- 关于POI操作Excel
公共接口Workbook http://poi.apache.org/apidocs/dev/org/apache/poi/ss/usermodel/Workbook.html
- 用 Spark 处理复杂数据类型(Array、Map、JSON字符串等)
split 对列表进行切割,然后生产新的列表 from pyspark.sql.functions import split# 对 key列按照 0-9之间的数字进行风格 重新命名为 s df.se ...
- 内网监控zabbix
告警 告警方式:linkedsee 类型:使用脚本linkedsee.sh [root@zabbix-server ~]# cat linkedsee.sh #! /bin/bash SERVICE_ ...
- java中list和map的底层实现原理
Collection(单列集合) List(有序,可重复) ArrayList 底层数据结构是数组,查询快,增删慢 线程不安全,效率高 Vector 底层数据结构是数组,查询快,增删慢 线程安全,效率 ...
- hdu3715 Go Deeper[二分+2-SAT]/poj2723 Get Luffy Out[二分+2-SAT]
这题转化一下题意就是给一堆形如$a_i + a_j \ne c\quad (a_i\in [0,1],c\in [0,2])$的限制,问从开头开始最多到哪条限制全是有解的. 那么,首先有可二分性,所以 ...
- css居然有根据容器宽度自动截取长度加省略号功能,强大!!
作者:☆威廉古堡♂ 项目中最初的做法(js截取): //字符长度截取包括中英文混合 function subStr(str, len) { str = str.toString(); var newL ...
- Fiddler 显示客户端请求时间,请求耗时,服务器地址
# 效果图 打开 CustomRules.js (C:\Users\UsersName\Documents\Fiddler2\Scripts):打开 fiddler 时 windows 快捷键 -&g ...