Datagrid自动滚动以使最后一行可见

时间:2014-02-07 14:21:56

标签: wpf silverlight

如何使DataGrid始终保持最后一行可见? 与添加新项目时自动滚动到底部一样

4 个答案:

答案 0 :(得分:3)

是的,您可以使用方法ScrollIntoView将DataGrid项传递给此方法。

<强> XAML:

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

<强>代码:

 private ObservableCollection<User> _users;


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

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

将新项添加到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]);
}

答案 1 :(得分:2)

这是一个使用LoadingRow事件的简单方法:

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

请记住在网格加载完成后禁用它。

答案 2 :(得分:0)

经过多种尝试,这是最好的方法:

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();
                }
            }

答案 3 :(得分:0)

最简单的方法:

DataGrid.SelectedIndex = DataGrid.Items.Count - 1; // If you need to select the last item
DataGrid.ScrollIntoView(DataGrid.Items[DataGrid.Items.Count - 1]);