我们有一个非常简单的应用程序,可通过蓝牙连接读取数据并更新页面上的文本字符串。所有更新都可以通过计时器正常运行,但是当我们切换到应用程序中的其他页面并返回首页时,更新将停止工作。我们可以在文本字符串更新上设置一个断点,我们可以看到新值,但它不会更新。
为什么当我们切换到其他页面并返回时会停止更新?这是一个简单的标签,并且已在用户界面中进行了更新?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Plugin.BLE;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Custom_TestAppHarness
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Homepage : ContentPage, INotifyPropertyChanged
{
public Homepage()
{
InitializeComponent();
// Start timer to update all the information on the home activity
if (App._timeerhasstarted == false)
{
App._timeerhasstarted = true;
Device.StartTimer(TimeSpan.FromSeconds(5), () =>
{
Task.Run(() =>
{
testcall();
});
return true; //use this to run continuously
});
}
}
void testcall()
{
Device.BeginInvokeOnMainThread(async () =>
{
BTTextStatus.Text = App._vehiclefuellevel.ToString();
});
}
protected override void OnAppearing()
{
base.OnAppearing();
BTTextStatus.Text = App._vehiclefuellevel.ToString();
}
}
}
标签的XML代码
<Label
x:Name = "BTTextStatus"
Grid.Row="2"
Grid.Column="0"
Grid.ColumnSpan="6"
HorizontalOptions="CenterAndExpand"
VerticalOptions="CenterAndExpand"
TextColor="#cccccc"
FontSize="Medium"/>
答案 0 :(得分:1)
解决方法是将组件从xaml中移出并将其添加到.cs文件中,以便在重新加载页面时再次引用这些组件。这是标签组件的示例,您需要在xaml网格布局中添加引用。
MainGrid.Children.Add(lblText = new Label()
{
TextColor = Color.FromHex("#cccccc"),
FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)),
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.CenterAndExpand,
}, 0, 2);
Grid.SetColumnSpan(lblText, 6);
在xaml代码中添加x:name引用,以便在我们重新加载页面时可以插入组件
<Grid x:Name="MainGrid" HorizontalOptions="CenterAndExpand" RowSpacing="0" ColumnSpacing="0">