如何在wp7中使用observable collection绑定列表框项?

时间:2012-06-12 10:02:09

标签: windows-phone-7

我的代码:

 ObservableCollection<SampleCheckedData> interestrates = new ObservableCollection<SampleCheckedData>();
 XDocument xmlDocu = XDocument.Load(new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(result)));

                interestrates = (from rts in xmlDocu.Descendants("Friend")

                                 select new SampleCheckedData
                                 {

                                     Id = (string)rts.Element("userid"),
                                     Name = (string)rts.Element("name"),
                                     Icon = (string)rts.Element("imageurl"),
                                     VisibleStatus = (string)rts.Element("visiblestatus"),
                                     AppStatus = (string)rts.Element("loginstatus"),

                                     imgBubble =bitmapRed,
                                 }).ToList<SampleCheckedData>();

然后获取错误,无法将system.collection.generic.list隐式转换为system.collection.observablecollection,如此。如何使用observable collection绑定列表框项目?

编辑:

Button b = sender as Button;
                    var res = interestrates.Where(a => a.Id.Equals(((System.Windows.FrameworkElement)(e.OriginalSource)).Tag)).ToList();
                    if (res.Count == 1)
                        interestrates.Remove(res.First());
                    interestrates = new ObservableCollection<SampleCheckedData>();
                    lstFriendRequuest.ItemsSource = "";
                    bindGetFriends();

这里成功删除了列表中的项目,但是在新绑定项目之后调用bindGetFriends()之后,我没有得到新项目获取旧项目。为什么服务返回旧项目列表?

2 个答案:

答案 0 :(得分:3)

使用此扩展程序:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

public static class Extensions
{
    public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> collection)
    {
        var observableCollection = new ObservableCollection<T>();
        foreach (var item in collection) observableCollection.Add(item);
        return observableCollection;
    }
}

用法:

interestrates = (from rts in xmlDocu.Descendants("Friend") 
    select new SampleCheckedData
    {    
        Id = (string)rts.Element("userid"),
        Name = (string)rts.Element("name"),
        Icon = (string)rts.Element("imageurl"),
        VisibleStatus = (string)rts.Element("visiblestatus"),
        AppStatus = (string)rts.Element("loginstatus"),    
        imgBubble =bitmapRed,
    }).ToObservableCollection<SampleCheckedData>();

答案 1 :(得分:1)

将Observable集合更改为List,

List<SampleCheckedData> interestrates = new List<SampleCheckedData>();

您还可以将List绑定到ListBox,而不是ObservableCollection

要解决从列表框中删除所选项目的其他问题,请尝试以下代码:

 var selectedIndex = listbox.SelectedIndex;
 var listItems = listbox.ItemsSource as List<SampleCheckedData>;
 listItems.RemoveAt(selectedIndex);
 listbox.ItemsSource = null;
 listbox.ItemsSource = listItems;

如果您仍然遇到问题,请告诉我