第一个列表框滚动条移动应该影响第二个列表框滚动条移动?但是如何? [英] First Listbox scrollbar movement should effect Second Listbox scrollbar movement? But How?

查看:26
本文介绍了第一个列表框滚动条移动应该影响第二个列表框滚动条移动?但是如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 WPF 应用中有 4 个列表框.它们中的每一个,在任何给定的时间点都包含相等的 no.其中的字符串 ListBoxItems.如果其中任何一个的选定索引发生变化,其他三个也会反映相同的行为.我想要的是,当用户移动其中一个的滚动条时,其他三个也应该同时移动.

I have 4 List Boxes in my WPF App. Each of them, at any given point of time contains equal no. of String ListBoxItems in them. If selected index of any one of them changes the other three also reflect the same behaviour. What i want is that when a user moves scrollbar of one of them the other three should also move simultaneoulsly.

我尝试了 Scrollintoview 但它不起作用 bcoz 如果我选择一个列表框的一个项目并将 scrollintoview 应用到其他三个列表框,它们中的所选项目位于顶部.

I tried Scrollintoview but it does not work bcoz if i select an item of a listBox and apply scrollintoview for other three Listboxes the selected item in them come on the top.

这就是为什么我认为滚动条移动应该是最好的选择.如何做到这一点?

That's why i think scrollbar movement should be the best option for this. How to do that?

推荐答案

在 XAML 中挂钩 ScrollChanged 事件

In XAML hook the ScrollChanged event

ScrollViewer.ScrollChanged="ListBox_ScrollChanged"

在 CodeBehind 中找到 ListBoxes 内的 Scrollviewers 并应用垂直偏移:

In CodeBehind find the Scrollviewers inside the ListBoxes and apply the Vertical offset:

    private void ListBox_ScrollChanged(object sender, ScrollChangedEventArgs e)
    {
      var sourceScrollViewer = FindVisualChild<ScrollViewer>(sender as DependencyObject) as ScrollViewer;
      var targetScrollViewer = FindVisualChild<ScrollViewer>(listBox2) as ScrollViewer;
      targetScrollViewer.ScrollToVerticalOffset(sourceScrollViewer.VerticalOffset);
    }

// helper method
    private childItem FindVisualChild<childItem>(DependencyObject obj)
    where childItem : DependencyObject
    {
      for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
      {
        DependencyObject child = VisualTreeHelper.GetChild(obj, i);
        if (child != null && child is childItem)
          return (childItem)child;
        else
        {
          childItem childOfChild = FindVisualChild<childItem>(child);
          if (childOfChild != null)
            return childOfChild;
        }
      }
      return null;
    }

这篇关于第一个列表框滚动条移动应该影响第二个列表框滚动条移动?但是如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆