问题描述
我有两个ItemsControls,使用相同的集合作为一个的ItemsSource。这两个ItemsControls的ItemTemplate非常相似:同时存在的DataTemplates内的ScrollViewer
I've got two ItemsControls, which use the same collection as an ItemsSource. ItemTemplates for both ItemsControls are very similar: there is a ScrollViewer inside both DataTemplates.
问:
如果我在第一个的ItemsControl生成的ScrollViewers之一变HorizontalOffset,我怎么可以从第二ItemsControl的滚动的ScrollViewer,具有相同的物体作为一个DataContext 后,以同样的HorizontalOffset?
If I change HorizontalOffset in one of the ScrollViewers generated in the first ItemsControl, how can I scroll the ScrollViewer from the second ItemsControl, which has the same object as a DataContext, to the same HorizontalOffset?
推荐答案
由于雷切尔提到的,可能有许多关于你的问题的解决方案。然而,我所看见的事都有点复杂或对我来说并不简单。所以,我以为这样一来,这是非常简单,可以将所有具有的ScrollViewer中的VisualTree控制。
As Rachel mentioned, there may be lots of solutions about your problem. However, the things that I have seen are a little complex or not simple for me. So, I thought this way, which is very simple and can apply all the control which has ScrollViewer in VisualTree.
以下code假定两个控件,具有的ScrollViewer中的VisualTree,在XAML中已经定义,它被命名为控制1 和控制2在我的$ C $ C。
The following code assumes that the two controls, having ScrollViewer in VisualTree, are already defined in Xaml, which are named control1 and control2 in my code.
public partial class MainWindow : Window
{
private ScrollViewer _scrollViewer1;
private ScrollViewer _scrollViewer2;
public MainWindow()
{
InitializeComponent();
Loaded += (s, e) =>
{
_scrollViewer1 = FindScrollViewer(**control1**);
_scrollViewer2 = FindScrollViewer(**control2**);
if (_scrollViewer1 == null || _scrollViewer2 == null) throw new InvalidOperationException();
_scrollViewer1.ScrollChanged += ScrollViewer1ScrollChanged;
_scrollViewer2.ScrollChanged += ScrollViewer2ScrollChanged;
};
}
private ScrollViewer FindScrollViewer(Visual visual)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++)
{
var visualChild = VisualTreeHelper.GetChild(visual, i) as Visual;
if (visualChild == null) continue;
var scrollViewer = visualChild as ScrollViewer;
if (scrollViewer != null)
{
return scrollViewer;
}
return FindScrollViewer(visualChild);
}
return null;
}
private void ScrollViewer1ScrollChanged(object sender, ScrollChangedEventArgs e)
{
_scrollViewer2.ScrollToVerticalOffset(_scrollViewer1.VerticalOffset);
}
private void ScrollViewer2ScrollChanged(object sender, ScrollChangedEventArgs e)
{
_scrollViewer1.ScrollToVerticalOffset(_scrollViewer2.VerticalOffset);
}
}
这篇关于在不同的DataTemplates创建了两个ScrollViewers之间共享HorizontalOffset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!