【发布时间】:2021-02-08 21:46:17
【问题描述】:
我有一个大约 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 以查看 Qty 是否已更改,但同时添加了新行(通过单击 Insert(0) 按钮)。在这种情况下,您会失去焦点,因为它一直向上滚动,因此您必须手动向下滚动。 我怎样才能防止这种情况发生?
【问题讨论】:
-
如果发生这种情况,您在将项目添加到源集合时做错了。听起来您正在使用
Action的NotifyCollectionChangedAction.Reset引发CollectionChanged事件。在ObservableCollection<T>上使用Insert方法应该没问题。 -
我正在修改这样的 ObservableCollection:this.Data.Insert(0, priceLadderRowData);
-
@RLaszlo:那么滚动位置不应该被重置。请提供您的问题的示例。
-
@mm8 我已经更新了我的问题。我希望它能澄清我的问题。