Updating an observable collection by querying or adding to a collection?

I have an observable collection represented as a property in a view model. The observed collection is loaded by objects from the data access level (linq2sql).

When a new item is added to the database through a different view model, what is the best way to update the observed collection? Should I re-populate the observed collection with a database query or directly insert a new object into the collection?

Also I'm still trying to figure out how to get one view model to interact with another, but I only used mvvm for 3 days.

+3
source share
4

. , , . , , .

:

class ViewModel1
{
    ObservableCollection<Object> entities;

    public ViewModel1()
    {
        EventsManager.ObjectAddedEvent += new EventHandler<ObjectAddedEventArgs>(EventsManager_ObjectAddedEvent);
        entities = new ObservableCollection<Object>();
    }

    void EventsManager_ObjectAddedEvent(object sender, ObjectAddedEventArgs e)
    {
        entities.Add(e.ObjectAdded);
    }
}

class EventsManager
{
    public static event EventHandler<ObjectAddedEventArgs> ObjectAddedEvent;

    public static void RaiseObjectAddedEvent(Object objectAdded)
    {
        EventHandler<ObjectAddedEventArgs> temp = ObjectAddedEvent;
        if (temp != null)
        {
            temp(null, new ObjectAddedEventArgs(objectAdded));
        }
    }
}

class ObjectAddedEventArgs : EventArgs
{
    public Object ObjectAdded { get; protected set; }

    public ObjectAddedEventArgs(Object objectAdded)
    {
        ObjectAdded = objectAdded;
    }
}

class ViewModel2
{
    public void AddObject(Object o)
    {
        EventsManager.RaiseObjectAddedEvent(o);
    }
}
+2

( ), , . , - Message Broker .

, . Observable , , . , .

+1

, DataContext DataContext, DataContext , .

DataContext , Ok Cancel , " ". DataContexts. DataContext , , , - , ( , ).

This solution took some time to execute the code, but it works beautifully. I also use the exact same mechanism to send changes to the parent DataContext on the server that is used by other clients, so everyone has updated data and high caching performance. I even use it to communicate with my background data store.

0
source

Source: https://habr.com/ru/post/1750447/


All Articles