问题
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