简体   繁体   中英

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()
        {

        }
    }

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());
}

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