我在Visual Studio 2013中使用Windows Phone Databound应用程序创建应用程序。 我正在使用如下的ObservableCollection:
public ObservableCollection<ItemViewModel> Items { get; private set; }
,此Items是LongListSelector的ItemSource。
一旦应用程序启动一切正常。在我的应用中,应用栏中有一个刷新按钮。 我想,当我点击刷新按钮时,ObservableCollection将显示更新的值,但ObservableCollection不刷新。
点击刷新按钮,我正在调用App.ViewModel.LoadData();
函数,它以json格式从网上下载一些信息。
我正在使用的代码如下:
public void LoadData()
{
if( IsDataLoaded )
this.Items = new ObservableCollection<ItemViewModel>();
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new System.Uri("http://questoons.com/"));
}
private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Showing the exact error message is useful for debugging. In a finalized application,
// output a friendly and applicable string to the user instead.
System.Windows.MessageBox.Show(e.Error.Message);
});
}
else
{
//System.Windows.Data.CollectionViewSource.GetDefaultView(this.Items).Refresh();
int i = 0;
dynamic dynJson = JsonConvert.DeserializeObject(e.Result);
foreach (var item in dynJson)
{
String bodyText = "";
bodyText += "Description:\n";
bodyText += (String)item.description;
this.Items.Add(new ItemViewModel()
{
ID = i.ToString(),
AppID = "lc-details-001",
Title = (String)item.title,
SenderID = "",
SenderName = "",
Time = "",
Type = "information",
Body = bodyText,
ValidTill = "",
Subtitle = (String)item.subtitle,
Icon = "",
Image = "",
ResponseURL = "",
ResponseOptions = ""
});
i++;
}
this.IsDataLoaded = true;
}
}
那么如何更新ObservableCollection?
答案 0 :(得分:2)
好的数据不更新的原因是您将可观察集合设置为新实例。将LoadData函数更新为:
public void LoadData()
{
if( IsDataLoaded )
this.Items.Clear();
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new System.Uri("http://questoons.com/"));
}
如果您更新了收藏集的实例,则必须使用RaisePropertyChanged通知用户界面。
答案 1 :(得分:1)
else
{
int i = 0;
var dynJson = JsonConvert.DeserializeObject<ItemViewModel>(e.Result);
foreach (var item in dynJson)
{
String bodyText = "";
bodyText += "Description:\n";
bodyText += (String)item.description;
this.Items.Add(item);
i++;
}
this.IsDataLoaded = true;
}