2

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 !

Community
  • 1
  • 1
Thomas Joulin
  • 6,590
  • 9
  • 53
  • 88
  • 1
    Note (in case you didn't know): if you are just displaying the items (without adding/removing) then you don't need to use an ObservableCollection. An IEnumerable will work fine. – Francesco De Vittori Nov 24 '10 at 22:23

3 Answers3

1

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);   
AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
0

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.

Matt Lacey
  • 65,560
  • 11
  • 91
  • 143
0

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);
        }
    }
}
Rover
  • 2,203
  • 3
  • 24
  • 44