![](/img/trans.png)
[英]Property value doesn't update value to Label in UI in Xamarin Forms
[英]Xamarin Forms - update a label value
昨晚,我花了5個小時試圖弄清楚如何在Xamarin Forms中更新標簽值,但卻一無所獲。
我的xaml看起來像這樣:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Meditation.HomePage">
<ContentPage.Content>
<Button Text="{Binding SelectedSound}" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" Clicked="OnButtonClicked" />
</ContentPage.Content>
我的主頁類如下所示:
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace Meditation
{
public partial class HomePage : ContentPage
{
public String SelectedSound { get; set; }
public HomePage()
{
InitializeComponent();
this.Title = AppInfo.AppName;
}
protected override void OnAppearing()
{
ShowSelectedSound();
BindingContext = this;
}
protected override void OnDisappearing()
{
DependencyService.Get<IAudio>().StopAudio();
}
// User Actions
void OnButtonClicked(object sender, EventArgs args)
{
Navigation.PushAsync(new SoundSelectionPage());
}
// Private
private void ShowSelectedSound()
{
if (Application.Current.Properties.ContainsKey(AppInfo.keySoundSelected))
{
SelectedSound = Application.Current.Properties[AppInfo.keySoundSelected] as string;
}
else
{
this.SelectedSound = "Choose sound";
}
}
}
}
首次加載頁面時,該按鈕正確顯示為“選擇聲音”文本。 但是,當返回application.current.properties鍵值時,它無法更新文本。
任何人都知道為什么標簽似乎僅在頁面首次加載而不進行時才更新。 更重要的是,任何人都可以提供代碼來使按鈕文本在初始設置后進行更新嗎?
您必須在homepage
類中實現INotifyPropertyChanged
才能更新頁面。
public partial class HomePage : ContentPage, INotifyPropertyChanged
{
private string selectedSound;
public string SelectedSound
{
get
{
return selectedSound;
} set
{
if (selectedSound!=value)
{
selectedSound = value;
this.OnPropertyChanged("SelectedSound");
}
}
}
.....
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName){
if (PropertyChanged != null {
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));}}
}
但我建議實現MVVM pattern
並定義一個ViewModel
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.