Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF/MVVM: Sync scrolling of two datagrids in different views

I have two datagrids side by side bound to different data tables and each with their own view.

The datatables both have the same number of rows, and I want both grids to maintain the same scroll position.

I am having trouble finding a way to do this using MVVM... anyone have any ideas?

Thanks! -Steven

like image 648
stevosaurus Avatar asked May 14 '10 19:05

stevosaurus


3 Answers

Take a look at codeproject Scroll Synchronization

like image 123
volody Avatar answered Oct 27 '22 01:10

volody


I was able to overcome this issue via some reflection hacks:

<DataGrid Name="DataGrid1" ScrollViewer.ScrollChanged="DataGrid1_ScrollChanged" />
<DataGrid Name="DataGrid2" />

and the code itself is:

    private void DataGrid1_ScrollChanged(object sender, ScrollChangedEventArgs e)
    {
        if (e.HorizontalChange != 0.0f)
        {
            ScrollViewer sv = null;
            Type t = DataGrid1.GetType();
            try
            {
                sv = t.InvokeMember("InternalScrollHost", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty, null, DataGrid2, null) as ScrollViewer;
                sv.ScrollToHorizontalOffset(e.HorizontalOffset);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
like image 33
Sergey Kuznetsov Avatar answered Oct 26 '22 23:10

Sergey Kuznetsov


The Scroll Synchronization project doesn't work for Datagrid because it doesn't expose ScrollToVerticalOffset

like image 40
Michael Avatar answered Oct 27 '22 00:10

Michael