问题
I want to be able do refresh my datagrid, because I am updating my table on my database datagrid and want to see the changes in grid , is there any way of automatically updating datagrid for every 1 minute?
回答1:
DataGrid.Items.Refresh()
will refresh the items. You can then use a timer to run every minute to force the refresh
Here is an example of implementing a timer to update a ListBox which you can adapt for your purpose.
回答2:
Going forward you can use ObservableCollection
to bind the grid so that you can avoid manual refreshes.
回答3:
I ended up using DispatcherTimer which simplified some threading issues for me:
private static DispatcherTimer _dataUpdateTimer = null;
private ObservableCollection<Item> _items;
public ObservableCollection<Item> Items
{
get { return _items; }
set
{
if (_items == value)
return;
_items = value;
this.OnPropertyChanged(nameof(Items));
}
}
private void SetupDataUpdateTimer()
{
_dataUpdateTimer = new DispatcherTimer();
_dataUpdateTimer.Tick += OnDataUpdateEvent;
_dataUpdateTimer.Interval = TimeSpan.FromMilliseconds(10000);
_dataUpdateTimer.Start();
}
private void OnDataUpdateEvent(object sender, EventArgs e)
{
this.Items = ... add or remove items
// ...
}
When I was previously just using a basic Timer
I was getting this error:
System.InvalidOperationException
HResult=0x80131509
Message=The calling thread cannot access this object because a different thread owns it.
Source=WindowsBase
StackTrace:
at System.Windows.Threading.Dispatcher.VerifyAccess()
at System.Windows.DependencyObject.GetValue(DependencyProperty dp)
at System.Windows.Controls.Primitives.Selector.get_SelectedValue()
at ...
at System.Timers.Timer.MyTimerCallback(Object state)
来源:https://stackoverflow.com/questions/6056098/how-can-i-refresh-my-datagrid-on-wpf-automatically-for-every-1-minute