I am using DataGrid for my application and I am using timer to update the datagrid from Database. The timer refreshes every 5 sec to see if there is new data. If there is any new data it updates in the datagrid. But it also resets everything in the datagrid and i loose selected index.
How do i prevent the selected item from updating or changing while other rows updates??
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);
}));
}
I already wrote in my comment that I would highly advice against manipulating your ItemsSource in your code-behind file (.xaml.cs) of your view.
Nevertheless I try to help you with your problem:
The problem you describe occurs because of setting the ItemsSource
property each tick of the timer. Maybe something like this could work:
// 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.
}));
}
You could try to save the index before you re-set the ItemsSource
and then set it back afterwards:
private void Timer1_Elapsed(object sender, ElapsedEventArgs e)
{
Application.Current.Dispatcher.Invoke((Action)(() =>
{
int index = dataGrid1.SelectedIndex;
dataGrid1.ItemsSource = AddData(dataGrid1);
dataGrid1.SelectedIndex = index;
}));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.