简体   繁体   中英

WP7 Insert all linq results in an ObservableCollection

I parse an xml results from a webservice using linq :

XElement items = XElement.Parse(e.Result);
MyListBox.ItemsSource = from item in items.Descendants("node")
            select new MyViewModel
            {
               ...
            };

This automatically populate my ListBox. But the problem is, I usually access my ObservableCollection like this :

App.MyViewModel.MyItems;

having in my xaml :

ItemsSource="{Binding MyItems,}"

How can I modify directly my ObservableCollection ? I read Cast LINQ result to ObservableCollection and tried this :

var v = from item in items.Descendants("node")
            select new MyViewModel
            {
               ...
            };
OApp.MyViewModel.MyItems = new ObservableCollection<MyViewModel>(v);

But I can't since this in WP7 (Silverlight 3), and there is no constructor like this

Thanks !

I'd just invent a static method like this:-

public static ObservableCollection<T> CreateObservableCollect<T>(IEnumerable<T> range)
{
    var result = new ObservableCollection<T>();
    foreach (T item in range)
    {
        result.Add(item);
    }
    return result;
}

Now your last line of code becomes:-

 OApp.MyViewModel.MyItems = new CreateObservableCollection<MyViewModel>(v);   

The constructor you're trying to use is in Silverlight, just not available on the phone. (as per MSDN )

Unfortunately, you'll have to populate your ObservableCollection yourself.

Do you need ObservableCollection? Do you need add or delete objects from collection or just update?

If only update, you can change MyViewModel.MyItems to:

public MyTypeOfCollection MyItems
{
    get { return _myItems; }
    set
    {
        _myItems = value;
        OnNotifyPropertyChanged("MyItems");//invoke INotifyPropertyChanged.PropertyChanged
    }
}

If you need adding or deleting of items, you can extend your collection to:

public static class Extend
{
    // Extend ObservableCollection<T> Class
    public static void AddRange(this System.Collections.ObjectModel.ObservableCollection o, T[] items)
    {
        foreach (var item in items)
        {
            o.Add(item);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM