Xamarin 更新标签已因更改为其他活动而终止



我们有一个非常简单的应用程序,它通过蓝牙连接读取数据并更新页面上的文本字符串。所有更新都通过计时器正常工作,但是当我们切换到应用程序中的其他页面并返回主页时,更新将停止工作。我们可以在文本字符串更新上设置断点,我们可以看到新值,但它不会更新。

为什么当我们更改为其他页面并返回时会停止更新?这是一个简单的标签,并且已在UI中更新?

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"/>

解决方法是从 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);

将 x:name 引用添加到 xaml 代码中,以便在我们重新加载页面时插入组件

<Grid x:Name="MainGrid" HorizontalOptions="CenterAndExpand" RowSpacing="0" ColumnSpacing="0">

最新更新