昨晚我花了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";
}
}
}
}
按钮正确显示文字为&#39;选择声音&#39;页面首次加载时但是,当我回到此页面时,当application.current.properties键值存在时,它无法更新文本。
任何人都知道为什么标签只在页面首次加载而不是正在进行时才会更新。更重要的是,任何人都可以提供代码,以便在最初设置后更新按钮文本吗?
答案 0 :(得分:2)
您必须在INotifyPropertyChanged
课程中实施homepage
才能更新页面。
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
。