简体   繁体   中英

Silverlight DataServices add items dynamically to the collection

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?

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

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