Silverlight DataServices add items dynamically to the collection

100 views Asked by At

I've a Datagrid which consumes a WCF DataService. Below is the code I am using;

public partial class MainPage : UserControl
{
    static ServiceReference1.SampleDbEntities entities = new ServiceReference1.SampleDbEntities(new Uri("http://localhost:1324/WcfDataService1.svc/"));
    static DataServiceQuery<ServiceReference1.Book> query = entities.Books.IncludeTotalCount();
    static WcfDataServicesDataSourceProvider<ServiceReference1.Book> context = new WcfDataServicesDataSourceProvider<ServiceReference1.Book>(query, entities);

    public MainPage()
    {
        Xceed.Silverlight.DataGrid.Licenser.LicenseKey = "****-A7K1K-****-BBUA";
        this.DataContext = context;
        InitializeComponent();
    }
}

Now I need to the newly added items to the grid without refreshing it. I have seen that I can use "context.NotifyItemsAdded" for this.

How do I fetch newly added items and insert them into the grid? Can I enumerate through the currently loaded items?

1

There are 1 answers

0
123 456 789 0 On BEST ANSWER

It would be best if you use ObservableCollection and set that one as the DataContext, newly added items will be automatically insert into the Grid.

I don't know of any graphical tutorial of ObservableCollection. The ObservableCollection class is a collection type (like List) which means that it holds objects of a given type T. What makes ObservableCollection special is that it "tells" observers when a new object is added or when an object is removed. This is especially useful for UI's implemented using WPF, because esentially, when an object is added to or removed from an observable collection, the UI is automatically updated. This happens because, when binding to an observable collection, WPF automatically adds an event handler to the ObservableCollecion's CollectionChanged event.

A useful tutorial is found here