阻止在DataGrid中刷新选定的行

时间:2017-08-21 15:47:36

标签: c# wpf datagrid logic selecteditem

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

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

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);
    }));
}

2 个答案:

答案 0 :(得分:0)

我已经在评论中写道,我强烈反对在您的视图的代码隐藏文件(.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.
    }));
}

答案 1 :(得分:0)

您可以尝试在重新设置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;
    }));
}