首页 > 解决方案 > 如何从文件后面的代码中不断刷新网格的内容

问题描述

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

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 子句,但不会初始化并显示新页面。

我认为这根本不是最佳做法,我想建议如何做得更好。

标签: androidxamarinxamarin.formscross-platform

解决方案


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

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

推荐阅读