Mark Denom
Mark Denom

Reputation: 1067

How do I properly append data to my collection using MVVM?

So I have created a service that is going to connect to my database and grab a few proxies every here and there so it's going to be doing is contiguously, I am going to have to make it async or with a backgroundworker so it won't deadlock the UI.

However, I've gotten to the part where I've setup my relay command and I want to invoke that function that grabs the proxies.

I have created a service that has the function in it, I didnt add the connecting stuff etc yet so this is mostly hypothetical but the question still stands.

public class ProxyDeliveryService
    {
        public ProxyDeliveryService()
        {

        }

        public Proxy GrabProxy()
        {
            //Do work..

            //Return the proxy
            return null;
        }
    }

How do I append the data to my collection in my ViewModel with a good MVVM approach? No singletons or anything like that. This here is throwing an error because it's expecting a delegate with a object parameter. Action<object> and a predicate so just like any other RelayCommand

public class ProxyContainerViewModel : ObservableObject
    {
        private ProxyDeliveryService pds = new ProxyDeliveryService();
        public ObservableCollection<Proxy> Proxies { get; set; } = new ObservableCollection<Proxy>();


        public RelayCommand Grabproxies { get; set; } = new RelayCommand(pds.GrabProxy(), true);

        public ProxyContainerViewModel()
        {

        }
    }

Upvotes: 0

Views: 50

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61369

I think you are overcomplicating this. What's wrong with:

public ICommand Grabproxies { get; set; } = new RelayCommand(CreateProxy, true);


private void CreateProxy(object param)
{
    Proxies.Add(pds.GrabProxy());
}

Upvotes: 1

Related Questions