我有一个大约有 500 行的 DataGrid。如果我向下滚动让我们排不。 200 并且一个新行被添加到顶部(集合的开始)它会自动向上滚动到第一行,所以我必须再次手动向下滚动。 我怎样才能防止这种情况发生?
这是一个示例应用程序来说明问题:
MainWindow.xaml.cs:
using System.Collections.ObjectModel;
using System.Windows;
namespace Testnamespace
{
public class TestClass
{
private int price;
private int qty;
public int Price { get => price; set => price = value; }
public int Qty { get => qty; set => qty = value; }
public TestClass(int price,int qty)
{
this.Price = price;
this.Qty = qty;
}
}
public partial class MainWindow : Window
{
private ObservableCollection<TestClass> data = new ObservableCollection<TestClass>() { new TestClass(3, 1), new TestClass(2, 1), new TestClass(1, 1) };
public ObservableCollection<TestClass> Data { get => data; set => data = value; }
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
private void InsertButton_Click(object sender, RoutedEventArgs e)
{
Data.Insert(0, new TestClass(Data.Count, 1));
}
}
}
XAML:
<Window x:Class="Testnamespace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Testnamespace"
mc:Ignorable="d"
Title="MainWindow" Height="300" Width="200">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition MinHeight="80"/>
</Grid.RowDefinitions>
<Button x:Name="InsertButton" Content="Insert(0)" Click="InsertButton_Click" Grid.Column="0" Height="20" Width="50" Background="Red"/>
<DataGrid x:Name="dataGrid"
Grid.Row="1"
AutoGenerateColumns="False"
ItemsSource="{Binding Data, IsAsync=True}"
MaxWidth="800"
MaxHeight="1600"
Width="100"
Height="100"
>
<DataGrid.Columns>
<DataGridTextColumn Header="Price" Binding="{Binding Price}">
</DataGridTextColumn>
<DataGridTextColumn Header="Qty" Binding="{Binding Qty}">
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
假设您想关注 price=1 以查看数量是否已更改,但同时添加了新行(通过单击 Insert(0) 按钮)。在这种情况下,您会失去焦点,因为它一直在向上滚动,因此您必须手动向下滚动。 我怎样才能防止这种情况发生?
答案 0 :(得分:0)
您可以手动滚动另一个 18.96 DIP,这是 Height
的默认 DataGridRow
:
private void InsertButton_Click(object sender, RoutedEventArgs e)
{
ScrollViewer scrollViewer = FindVisualChild<ScrollViewer>(dataGrid);
double offset = scrollViewer.VerticalOffset;
Data.Insert(0, new TestClass(Data.Count, 1));
if (offset > 0)
scrollViewer.ScrollToVerticalOffset(offset + 18.96);
}
private static T FindVisualChild<T>(Visual visual) where T : Visual
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++)
{
Visual child = (Visual)VisualTreeHelper.GetChild(visual, i);
if (child != null)
{
T correctlyTyped = child as T;
if (correctlyTyped != null)
return correctlyTyped;
T descendent = FindVisualChild<T>(child);
if (descendent != null)
return descendent;
}
}
return null;
}