Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# WPF DataGrid ScrollIntoView not working with touch

I try to scroll to the last selected item in a WPF DataGrid on the Loaded event. The DataGrid sits in a Tab. Everything is working when I test it in a normal Windows environment. But as soon as I touch the TabPage on a tablet instead of clicking it, it doesn't scroll to my last selected item. This is my code so far:

private void dataGrid_Loaded(object sender, RoutedEventArgs e)
{
    var currentItem = dataGrid.SelectedItem;

    dataGrid.ItemsSource = sh.GetDataTable(<SQL Select statement>).DefaultView;

    if (!(currentItem == null))
    {
        dataGrid.ScrollIntoView(currentItem);
    }
}

I've also tried the solution I found here but it didn't work.

Edit:

For testing purposes I completely removed the dataGrid_Loaded event. Now I'm only loading data into the DataGrid at the start of the program. Even now it keeps the scroll position when I switch between tabs with mouse clicks but not with touch! Is this a bug in the .NET Framework?

like image 692
toXel Avatar asked Oct 21 '25 06:10

toXel


1 Answers

With the help of the MSDN Community I was able to solve the problem.

I had to scroll to the end of the DataGrid, do a UpdateLayout() and then scroll to the Item I want. Additionally I can't just set the ItemsSource every time because then the Item I saved before is not a valid Item of the DataGrid anymore.

So finally my dataGrid_Loaded method looks like this:

private void dataGrid_Loaded(object sender, RoutedEventArgs e)
{
    object currentPos = dataGrid.SelectedItem;

    if (dataGrid.ItemsSource == null)
    {
        dataGrid.ItemsSource = sh.GetDataTable("<SQL query>").DefaultView;
    }
    else
    {
        dataGrid.Items.Refresh();
    }

    if (currentPos != null)
    {
        dataGrid.ScrollIntoView(dataGrid.Items[dataGrid.Items.Count - 1]);
        dataGrid.UpdateLayout();
        dataGrid.ScrollIntoView(currentPos);
    }
}

I hope this will help someone else who has the same problem.

For reference here is my german MSDN thread in which my problem was solved.

like image 148
toXel Avatar answered Oct 23 '25 20:10

toXel