wpf Datagrid 自动滚动以使最后一行可见
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21630124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Datagrid auto scroll to make last row visible
提问by Magnus Ahlin
How do you make a DataGrid always keeping the last row visible? As in automatically scrolling to the bottom when new items are added
如何让 DataGrid 始终保持最后一行可见?就像添加新项目时自动滚动到底部一样
回答by Jan
Yes, you can use method ScrollIntoViewa pass DataGrid item to this method.
是的,您可以使用ScrollIntoView方法将 DataGrid 项传递给此方法。
XAML:
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:
向 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]);
}
回答by babakansari
This is a simple approach using LoadingRow event:
这是使用 LoadingRow 事件的简单方法:
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.
请记住在网格加载完成后禁用它。
回答by Loran
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();
}
}

