UWP 更新 UIThread 中的 Button 内容

UWP update Button content in UIThread

我有一个执行后台任务的按钮(它从 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");
        });
    }

按钮位于MainPage中Frame的一个页面(SettingsPage)中。在我切换到另一个页面并变回SettingsPage后,按钮停止更新内容,尽管线程仍然是运行。

如何保持按钮内容更新?

将页面保留在缓存中。将 NavigationCacheMode 属性 设置为启用或必需。

在 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
    }
}

Read more about NavigationCacheMode

只需将 NavigationCacheMode 设置为 Enabled