如何从Xamarin.forms中的事件更改TextView中的文本
本文关键字:TextView 文本 事件 Xamarin forms | 更新日期: 2023-09-27 18:21:29
我在原生PageRenderer(Android)中使用Xamarin.Forms,并实现了Geolocator(https://github.com/XLabs/Xamarin-Forms-Labs/wiki/Geolocator)用于在位置更改时使用OnPositionChanged事件。但在他们使用的原始代码中:
private void OnPositionChanged(object sender, PositionEventArgs e)
{
BeginInvokeOnMainThread (() => {
ListenStatus.Text = e.Position.Timestamp.ToString("G");
ListenLatitude.Text = "La: " + e.Position.Latitude.ToString("N4");
ListenLongitude.Text = "Lo: " + e.Position.Longitude.ToString("N4");
});
}
它在我的应用程序上不起作用,现在我实现了这样的东西:
private void OnPositionChanged(object sender, PositionEventArgs e)
{
_activity.RunOnUiThread(() => {
_listenStatus.Text = "Estado:" + e.Position.Timestamp.ToString("G");
_listenLatitude.Text = "Latitud: " + e.Position.Latitude.ToString("N4");
_listenLongitude.Text = "Longitud: " + e.Position.Longitude.ToString("N4");
});
}
当我的OnElementChanged像:
protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
{
base.OnElementChanged (e);
_activity = this.Context as Activity;
_activity.SetContentView (Resource.Layout.RequestService);
_view = _activity.LayoutInflater.Inflate(Resource.Layout.RequestService, this, false);
AddView (_view);
SetupElements ();
SetupGeolocator ();
}
以及我的SetupElements:
void SetupElements ()
{
_listenStatus = _view.FindViewById<TextView> (Resource.Id.ListenStatus);
_listenLatitude = _view.FindViewById<TextView> (Resource.Id.ListenLatitude);
_listenLongitude = _view.FindViewById<TextView> (Resource.Id.ListenLongitude);
}
但它不起作用,数据检索成功,TextViews加载成功,当RunOnUiThread运行时,视图中没有任何变化。
您可以在自定义渲染器中使用静态页面来更改视图。
假设你有这样一个页面:;
public class SomePage : ContentPage
{
public static SomePage ThisPage {get; set;}
Label label;
public SomePage()
{
ThisPage = this;
label = new Label();
}
}
在你的页面渲染器中,这样使用它:
SomePage.ThisPage.label.Text = "SomeText";
希望这能有所帮助。