Windows phone refresh/update listbox items

2019-09-01 11:45发布

问题:

I have a problem with a RSS feed app. When my app launches, the listbox gets the feeds and show them in my listbox, but when i press my refresh button the listbox never updates, it just show the same items again, but if i close the app, and then relaunch it, it will show the latest feeds. I hope there is someone that can help. Thanks.

MainWindow.xaml:

<ListBox Grid.Row="1" Name="feedListBox" ScrollViewer.VerticalScrollBarVisibility="Auto" SelectionChanged="feedListBox_SelectionChanged">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        ...
                        ...
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

MainWindow.cs:

private void appBarRefresh_Click(object sender, EventArgs e)
{
    feedListBox.ItemsSource = null;

    GetFeed(IsolatedStorageSettings.ApplicationSettings["key"].ToString());
}

private void GetFeed(string rss)
{
    WebClient webClient = new WebClient();

    webClient.DownloadStringAsync(new System.Uri(rss));
    webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
}

private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error != null)
    {
        Deployment.Current.Dispatcher.BeginInvoke(() =>
        {
            MessageBox.Show(e.Error.Message);
        });
    }
    else
    {
        this.State["feed"] = null;
        this.State.Clear();
        this.State["feed"] = e.Result;

        UpdateFeedList(e.Result);
    }
}

private void UpdateFeedList(string feedXML)
{
    StringReader stringReader = new StringReader(feedXML);
    XmlReader xmlReader = XmlReader.Create(stringReader);
    SyndicationFeed feed = SyndicationFeed.Load(xmlReader);

    Deployment.Current.Dispatcher.BeginInvoke(() =>
    {
        feedListBox.ItemsSource = feed.Items;
    });
    ;
}

UPD from comments:

In my OnNavigatedTo method I run this code:

if (this.State.ContainsKey("feed")) 
{ 
    if (feedListBox.Items.Count == 0) 
    { 
        UpdateFeedList(State["feed"] as string); 
    } 
}

回答1:

First of all update this method:

private void GetFeed(string rss)
{
    //register event handler first, then call the async method
    WebClient webClient = new WebClient();
    webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
    webClient.DownloadStringAsync(new System.Uri(rss)); 
}

update:

Looks like your request was cached by OS. What you can do to is to add some random text to your url.

webClient.DownloadStringAsync(new System.Uri(rss + "?disablecache="+Environment.TickCount));