【问题标题】:How to refresh the content of a grid continiously from the code behind file如何从文件后面的代码中不断刷新网格的内容
【发布时间】:2020-09-15 16:45:04
【问题描述】:

我尝试使用并行线程不断刷新网格的内容。那是不工作的代码:

private void ContiniouslyRefreshPage(int interval)
        {
            var startTimeSpan = TimeSpan.Zero;
            var periodTimeSpan = TimeSpan.FromSeconds(interval);           
            Dictionary<string, string> lastCheck = bluetoothService.CheckRequirements();
            var timer = new System.Threading.Timer((e) =>
            {
                Dictionary<string, string> newCheck = bluetoothService.CheckRequirements();
                if (!(lastCheck.Count == newCheck.Count && !bluetoothService.CheckRequirements().Except(lastCheck).Any()))
                {
                    Application.Current.MainPage = new MasterDetail
                    {
                        Detail = new NavigationPage(new TestingPage())
                        {
                            BarBackgroundColor = Color.White,
                            BarTextColor = Color.Black
                        }
                    };
                    lastCheck = newCheck;
                }
            }, null, startTimeSpan, periodTimeSpan);
        }

if 子句有效,因此只有在我的数据集发生更改时才应刷新页面(数据集由 CheckRequirements-Method 返回)

代码不工作:当有变化时它进入 if 子句,但它没有初始化和显示新页面。

我认为这根本不是最佳做法,我想请教一下如何做得更好。

【问题讨论】:

  • 你为什么要替换整个页面堆栈只是为了修改单个页面的内容?
  • 因为只有创建视图的线程才能修改它。所以我不能打开一个新线程,它每 3 秒检查一次更改以及从这个线程访问“主”线程创建的视图。
  • 非常感谢!
  • 更新UI操作应该在主线程中执行。尝试将相关功能代码放在主线程中。如:MainThread.BeginInvokeOnMainThread(() =&gt;{// Code to run on the main thread});.

标签: android xamarin xamarin.forms cross-platform


【解决方案1】:

更新 UI 操作应在主线程中执行。尝试将相关功能代码放在主线程中。如:

private void ContiniouslyRefreshPage(int interval)
{
    ...
    MainThread.BeginInvokeOnMainThread(() =>
    {
        Application.Current.MainPage = new MasterDetail
        {
            Detail = new NavigationPage(new TestingPage())
            {
                BarBackgroundColor = Color.White,
                BarTextColor = Color.Black
            }
        };
    };
}

【讨论】:

  • 谢谢!顺便提一下:@Jason 批评加载整个新页面是正确的。我刚刚调用了一个方法来更改主线程中 Grid 中的值。
猜你喜欢
  • 2013-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-23
  • 2010-12-26
  • 1970-01-01
  • 1970-01-01
  • 2015-04-06
相关资源
最近更新 更多