How Can I refresh my Datagrid on WPF automatically for every 1 minute?

心不动则不痛 提交于 2020-01-04 03:46:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!