Datagrid auto scroll to make last row visible

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-25 01:12:42

问题


How do you make a DataGrid always keeping the last row visible? As in automatically scrolling to the bottom when new items are added


回答1:


Yes, you can use method ScrollIntoView a pass DataGrid item to this method.

XAML:

<DataGrid x:Name="DataGrid" Grid.Row="1"
          Margin="5"
          AutoGenerateColumns="True"
          ItemsSource="{Binding Path=Users}">

Code:

 private ObservableCollection<User> _users;


    public ObservableCollection<User> Users
    {
        get
        {
            return _users;
        }

        set
        {
            _users = value;
            OnPropertyChanged("Users");
        }
    }

Add new item to DataGrid:

private void BtnAdd_OnClick(object sender, RoutedEventArgs e)
{
    Users.Add(new User { Id = Guid.NewGuid().ToString(), FirstName = "Bill", LastName = "Clinton" });

    //scroll to last added item
    DataGrid.ScrollIntoView(Users[Users.Count-1]);
}



回答2:


This is a simple approach using LoadingRow event:

void dataGrid_LoadingRow(object sender, System.Windows.Controls.DataGridRowEventArgs e)
{
    dataGrid.ScrollIntoView(e.Row.Item);
}

Just remember to disable it after grid loading is finished.




回答3:


After already try many way,this is the best way:

if (datagrid.Items.Count > 0)
            {
                var border = VisualTreeHelper.GetChild(datagrid, 0) as Decorator;
                if (border != null)
                {
                    var scroll = border.Child as ScrollViewer;
                    if (scroll != null) scroll.ScrollToEnd();
                }
            }


来源:https://stackoverflow.com/questions/21630124/datagrid-auto-scroll-to-make-last-row-visible

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!