昨晚我花了 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 模式
并改为定义一个 ViewModel
。
关于c# - Xamarin Forms - 更新标签值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41761627/