防止所选行在 DataGrid 中刷新

Prevent selected row from refreshing in DataGrid

我正在为我的应用程序使用 DataGrid,我正在使用计时器从数据库更新数据网格。计时器每 5 秒刷新一次以查看是否有新数据。如果有任何新数据,它会在数据网格中更新。但它也会重置数据网格中的所有内容,并且我会松开选定的索引。

如何防止所选项目在其他行更新时更新或更改?

DataGrid

public void InitTimer()
{
    Timer timer1 =  new Timer();
    timer1.Elapsed += Timer1_Elapsed;
    timer1.Interval = 5000; // in milliseconds
    timer1.Start();
}

private void Timer1_Elapsed(object sender, ElapsedEventArgs e)
{
    Application.Current.Dispatcher.Invoke((Action)(() =>
    {
        dataGrid1.ItemsSource = AddData(dataGrid1);
    }));
}

我已经在评论中写道,我强烈建议不要在您视图的代码隐藏文件 (.xaml.cs) 中操纵您的 ItemsSource

尽管如此,我会尽力帮助您解决问题:

出现您描述的问题是因为设置了 ItemsSource 属性 计时器的每个滴答声。也许这样的事情可以工作:

// This is the collection to bind your datagrid to
public ObservableCollection<YourObject> Data { get; } = new ObservableCollection<YourObject>();

// This method needs to be called once (preferably in the constructor)
private void InitDataGrid() 
{
    dataGrid1.ItemsSource = this.Data;
}

private void Timer1_Elapsed(object sender, ElapsedEventArgs e)
{
    Application.Current.Dispatcher.Invoke((Action)(() =>
    {
        // Here you need to call a method which modifies the Data property.
        // Try removing, inserting, updating the items directly to the collection.
        // Do not set the ItemsSource directly, instead manipulate the ObservableCollection.
    }));
}

您可以尝试在重新设置 ItemsSource 之前保存索引,然后再将其重新设置:

private void Timer1_Elapsed(object sender, ElapsedEventArgs e)
{
    Application.Current.Dispatcher.Invoke((Action)(() =>
    {
        int index = dataGrid1.SelectedIndex;
        dataGrid1.ItemsSource = AddData(dataGrid1);
        dataGrid1.SelectedIndex = index;
    }));
}