我目前正在使用页面上的静态方法(它是静态的,因为它可以与其他页面一起使用)。在这个方法的最后,我预先得到一个列表的结果,并给我的标签的x:name(我在我的XAML页面中创建)一个新文本。
要测试它是否有效我在日志中写出了标签文本,并且确实写出了正确的文本,但文本没有在应用程序上更新。
代码看起来像这样:
public static MyPage currentpage = new MyPage();
这是我正在处理的当前页面。为了达到标签x:name,我创建了这段代码。
然后这也是此页面上的静态方法。
public static async Task loadTheData(string token) //method is static because i send a token from another page
{
...
foreach (var profileinfo in App.registeredUsers) //this is my list
{
currentpage.myXAMLlabel.Text = profileinfo.name; //this is the label where i assign the new text
}
System.Diagnostics.Debug.WriteLine(currentpage.myXAMLlabel.Text); //the correct text gets written out in the log but the text does not get updated "visually" on the app
}
正如我上面提到的,我在日志中得到了正确的文本,但标签的文本没有得到更新,而且#34;在视觉上#34;在应用程序屏幕上。
我首先从特定的iOS / Android文件夹中调用静态方法:
App.SuccessfulLoginAction.Invoke();
在我的应用页面上,我有以下方法:
public static Action SuccessfulLoginAction
{
get
{
return new Action(async () =>
{
await MyPage.loadTheData(token);
});
}
}
我可以将SuccessfulLoginAction移至MyPage
,而不是在App
页面上。但是为了让iOS代码到达Action
,我认为该方法仍然是静态的(?)。
如何调整代码以解决此问题?
答案 0 :(得分:1)
确保更新UI /主线程上的任何UI元素,即:
Device.BeginInvokeOnMainThread(() =>
{
currentpage.myXAMLlabel.Text = profileinfo.name; //this is the label where i assign the new text
});
答案 1 :(得分:1)
如果我正确阅读了您的问题,您是在public static MyPage currentpage = new MyPage();
课程中添加MyPage
吗?
如果是这种情况,MyPage
变量中的currentPage
实例将与您在屏幕上看到的实例不同。 Debug消息将显示不在屏幕上的实例。你可以用单例模式实现你想要的东西。
使用MessagingCenter
删除静态或者更好的是,要摆脱静态,使用MessagingCenter
发布/订阅机制或任何其他MVVM等效。 MessagingCenter
的示例:
您可以将App类用作特定于平台的项目的发件人。像这样:
MessagingCenter.Send<App>((App)Xamarin.Forms.Application.Current, "myEvent")
在您的App类中订阅:
MessagingCenter.Subscribe<App>(this, "myEvent", ...)
如果您想在自己的页面中订阅:
MessagingCenter.Subscribe<App>((App)Application.Current, "myevent", ...)
有关详细信息,请参阅the docs。
更新右侧话题中的UI元素
您还应该确保更新主线程上的UI元素(由于您使用的是async / await,因此您可能不会使用它)。正如@SushiHangover在回答中提到的那样使用Device.BeginInvokeOnMainThread
:
Device.BeginInvokeOnMainThread(() =>
{
currentpage.myXAMLlabel.Text = profileinfo.name;
});