如何使DataGrid始终保持最后一行可见? 与添加新项目时自动滚动到底部一样
答案 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]);