我有一个执行背景任务的按钮(它从Internet搜索所有音乐文件的歌词)。并且它在获取歌词时通过增加计数器来更新按钮内容。
private async void AddLyrics_Click(object sender, RoutedEventArgs e)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
string format = Helper.LocalizeMessage("PostParenthesis");
HyperlinkButton button = (HyperlinkButton)sender;
int count = MusicLibraryPage.AllSongs.Count;
for (searchLyricsCounter = 1; searchLyricsCounter < count + 1; searchLyricsCounter++)
{
Music music = MusicLibraryPage.AllSongs[searchLyricsCounter - 1];
string lyrics = await music.GetLyricsAsync();
//if (string.IsNullOrEmpty(lyrics))
//{
// lyrics = await Controls.MusicLyricsControl.SearchLyrics(music);
// await music.SaveLyricsAsync(lyrics);
//}
System.Diagnostics.Debug.WriteLine(searchLyricsCounter);
button.Content = string.Format(format, addLyricsContent, searchLyricsCounter + "/" + count);
}
searchLyricsCounter = 0;
button.Content = Helper.Localize("AddLyrics");
Helper.ShowNotification("SearchLyricsDone");
});
}
该按钮位于主页中框架的页面(SettingsPage)中。当我切换到另一个页面并返回到SettingsPage后,该按钮停止更新内容,尽管该线程仍在运行。
如何保持按钮内容更新?
将页面保留在缓存中。将NavigationCacheMode属性设置为Enabled或Required。
在XAML上。
<Page NavigationCacheMode="Enabled">
</Page>
或隐藏在代码中
public sealed partial class SettingsPage : Page
{
public SettingsPage()
{
InitializeComponent();
NavigationCacheMode = NavigationCacheMode.Enabled;
}
}
单击事件已在UI线程上运行
private async void AddLyrics_Click(object sender, RoutedEventArgs e)
{
HyperlinkButton button = (HyperlinkButton)sender;
button.IsEnabled = false; // avoid duplicate clicks
try
{
string format = Helper.LocalizeMessage("PostParenthesis");
int count = MusicLibraryPage.AllSongs.Count;
int searchLyricsCounter = 1;
foreach(Music music in MusicLibraryPage.AllSongs)
{
string lyrics = await music.GetLyricsAsync();
System.Diagnostics.Debug.WriteLine(searchLyricsCounter);
button.Content = string.Format(format, addLyricsContent, searchLyricsCounter + "/" + count);
}
button.Content = Helper.Localize("AddLyrics");
Helper.ShowNotification("SearchLyricsDone");
}
finally
{
button.IsEnabled = true; // Can click now
}
}
只需将NavigationCacheMode
设置为Enabled
。