欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

WPF学习笔记(5):两个DataGrid的滚动条实现同步滚动

程序员文章站 2022-12-16 19:48:39
效果:两个DataGrid的滚动条实现同步滚动。 代码参考了博客园chuncn的文章《.net中同步多个ScrollViewer滚动的四种方法》,原文是针对ListBox的。现改为针对DataGrid,略微作了修改,代码以水平滚动条为例。 原文地址:https://www.cnblogs.com/c ......

效果:两个datagrid的滚动条实现同步滚动。

WPF学习笔记(5):两个DataGrid的滚动条实现同步滚动

 

代码参考了博客园chuncn的文章《.net中同步多个scrollviewer滚动的四种方法》,原文是针对listbox的。现改为针对datagrid,略微作了修改,代码以水平滚动条为例。

原文地址:

 

实现方法:

方法一:利用dependencyproperty类的registerattached方法,在属性系统上注册附加属性,并将滚动条属性值horizontaloffset通过注册属性关联到一个方法。

scrollviewer sv1, sv2;

private void window_loaded(object sender, routedeventargs e)
{
    //分别获取两个datagrid的scrollviewer
sv1 = visualtreehelper.getchild(visualtreehelper.getchild(this.datagrid1, 0), 0) as scrollviewer; sv2 = visualtreehelper.getchild(visualtreehelper.getchild(this.datagrid2, 0), 0) as scrollviewer; //将滚动条属性值horizontaloffset关联到onscrollchanged1方法
var offsetchangelistener = dependencyproperty.registerattached("listeneroffset1", typeof(object), typeof(usercontrol), new propertymetadata(onscrollchanged1)); var binding = new binding("horizontaloffset") { source = sv1 }; sv1.setbinding(offsetchangelistener, binding); offsetchangelistener = dependencyproperty.registerattached("listeneroffset2", typeof(object), typeof(usercontrol), new propertymetadata(onscrollchanged2)); binding = new binding("horizontaloffset") { source = sv2 }; sv2.setbinding(offsetchangelistener, binding); } public void onscrollchanged1(dependencyobject sender, dependencypropertychangedeventargs e) { double a = (double)e.newvalue; //获取滚动条位置变化后的属性值 sv2.scrolltohorizontaloffset(a); } public void onscrollchanged2(dependencyobject sender, dependencypropertychangedeventargs e) { double a = (double)e.newvalue; sv1.scrolltohorizontaloffset(a); }

 

方法二:利用滚动条的scrollchanged事件,同步两个滚动条的位置。

scrollviewer sv1, sv2;
private void window_loaded(object sender, routedeventargs e)
{
    //分别获取两个datagrid的scrollviewer
    sv1 = visualtreehelper.getchild(visualtreehelper.getchild(this.datagrid1, 0), 0) as scrollviewer;
    sv2 = visualtreehelper.getchild(visualtreehelper.getchild(this.datagrid2, 0), 0) as scrollviewer;

    //关联scrollchanged事件
    sv1.scrollchanged += new scrollchangedeventhandler(sv1_scrollchanged);
    sv2.scrollchanged += new scrollchangedeventhandler(sv2_scrollchanged);
}

void sv1_scrollchanged(object sender, scrollchangedeventargs e)
{
    sv2.scrolltohorizontaloffset(sv1.horizontaloffset);
}

void sv2_scrollchanged(object sender, scrollchangedeventargs e)
{
    sv1.scrolltohorizontaloffset(sv2.horizontaloffset);
}