public partial class ContactsList : PhoneApplicationPage
{
static ObservableCollection<Contact> dataSource { get; set; }
public ContactsList()
{
InitializeComponent();
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
dataSource.CollectionChanged += this.dataSource_CollectionChanged;
var tasks = new List<Task>();
for (int i = 1; i < 6; i++)
{
tasks.Add(GetContacts(i.ToString()));
}
await Task.WhenAll(tasks);
}
private void dataSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
List<AlphaKeyGroup<Contact>> DataSource = AlphaKeyGroup<Contact>.CreateGroups(dataSource, System.Threading.Thread.CurrentThread.CurrentUICulture, (Contact s) => { return s.Name; }, true);
ContactsLList.ItemsSource = DataSource;
}
public async Task GetContacts(string page)
{
try
{
string strCredidentials = Globals.APIKey;
string strAuthorization = Convert.ToBase64String(Encoding.UTF8.GetBytes(strCredidentials));
RestClient client = new RestClient(Globals.myURL);
RestRequest request = new RestRequest("/contacts.json?state=all&page=" + page);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Authorization", "Basic " + strAuthorization);
request.Method = Method.GET;
var rslt = client.ExecuteAsync(request, (r) =>
{
if (r.ResponseStatus == ResponseStatus.Completed)
{
if (r.Content == "" || r.Content == " ")
{
MessageBox.Show("No Contacts Found");
}
else
{
dataSource = new ObservableCollection<Contact>();
var conts = JsonConvert.DeserializeObject<List<ContactWrapper>>(r.Content);
foreach (ContactWrapper cont in conts)
{
try
{
string name = cont.User.Name;
string email = cont.User.Email;
string mobile = cont.User.Mobile;
string phone = cont.User.Phone;
string jobtitle = cont.User.JobTitle;
dataSource.Add(new Contact("", "", "", "", "", email, "", jobtitle, mobile, name, phone, ""));
}
catch { }
}
}
}
});
} catch {}
}
}
}
在GetContacts方法中添加了dataSource集合,因此想法是每次将返回数据添加到dataSource时调用GetContacts 6次。
当发生这种情况时,我想调用dataSource_CollectionChanged来更新XAMl页面上的绑定longlistselector。
有人可以告诉我哪里出错了吗?
由于
答案 0 :(得分:0)
我已经构建了simple example basing on your code,而且您的代码似乎还可以。
我认为问题可能出在GetContacts(string page)
中的任务// Do stuff here
中 - 检查您是否在UI中尝试更改某些内容,请使用Dispatcher执行此操作:
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
//do UI stuff here;
});
编辑 - 在讨论中发现收集品在开始时没有初始化。