S
S
Slavka2017-06-04 23:36:58
WPF
Slavka, 2017-06-04 23:36:58

Autoscroll does not work correctly in DataGrid, how to rewrite behavior?

In general, there is a task, there is a datagrid, SelectedIndex is set from outside it and you need something to autoscroll to the selected object immediately (well, as an addition, so that the next 5 objects can be seen). The whole problem is that the scroll does not reach the element that is far below the list, which is not visible now, for example, if I now see elements from 40-80, then it will not scroll automatically up to 120, but it will scroll up to 20.
Here is the Behavior code that I added to the datagrid

public class ScrollIntoViewBehavior : Behavior<DataGrid>
    {
        protected override void OnAttached()
        {
            AssociatedObject.SelectionChanged += new SelectionChangedEventHandler(AssociatedObject_SelectionChanged);
        }

        void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var dataGrid = (sender as DataGrid);
            dataGrid.UpdateLayout();
            dataGrid.ScrollIntoView(dataGrid.SelectedItem);
            
        }
    }

Xaml inside DataGrid tag
<i:Interaction.Behaviors>
                    <behaviors:ScrollIntoViewBehavior />
                </i:Interaction.Behaviors>

And the index setting code
public void SetFocusOnCommandByNumber(int index)
        {
            if ((index >= _commands.Count) || (SelectedIndex == index))
                return;
            if ((index + 5) < _commands.Count)
            {
                SelectedIndex = index + 5;
                SelectedIndex = index;
            }
            else
            {
                SelectedIndex = index;
            }
        }

The index comes from outside several times per second, so I excluded change signals if the value did not change.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question