开发者

MVVM: Delete a CustomerViewModel, but how to get the Customer model inside it?

I have a 开发者_Python百科list of CustomerViewModels in a ComboBox. The selected CustomerViewModel I want to delete and also the Customer wrapped inside it to remove it from the repository.

But how can I access the Customer model inside the CustomerViewModel?


Just a suggestion, make your collection of customerviewmodels an ObserableCollection of CustomerViewModels. what this buys you is a CollectionChanged Event that you could listen on with a delegate for changes to the collection ie deletion, so from there you could manipulate you model accordingly

http://msdn.microsoft.com/en-us/library/ms653375(VS.85).aspx

perhaps something like

public class CustomersViewModel: ViewModelBase
{
    public ObservableCollection<CustomersViewModel> Customers { get; private set; }

    public CustomersViewModel()
    {
        Customers = new ObservableCollection<CustomersViewModel>(GetCustomers());
        Customers.CollectionChanged += 
            (sender, args) =>
                {
                    if (args.Action ==  NotifyCollectionChangedAction.Remove)
                    {
                        foreach (CustomerViewModel customerViewModel in args.NewItems)
                        {
                            DeleteCustomer(customerViewModel.Customer);
                        }
                    }
                };
    }

    private void DeleteCustomer(Customer customer)
    {
        // Call into your repo and delete the customer.
    }

    private List<CustomersViewModel> GetCustomers()
    { 
        // Call into your model and return customers.
    }

    ... ICommands ect... 

}


You might have already access to the Customer inside CustomerViewModel (the VieModel needs to expose the properties of the Customer so the View can databind on them; I usually do it by exposing the Customer or a copy of it directly).

The point is that you should not delete the Customer yourself. That's what the ViewModel is for, to expose an ICommand that deletes the associated Customer. Depending on which MVVM framework you are using, look into DelegateCommand or another equivalent.

Your CustomerViewModel would have a

public ICommand DeleteCommand { get; private set; }

and your View would bind a CommandTarget (probably a Button) to this command. When the command is executed a private method of CustomerViewModel will be run, and you can delete the Customer from there without exposing the deletion mechanism to other parts of the code. For example:

public CustomerViewModel()
{
    this.DeleteCommand = new DelegateCommand(this.ExecuteDeleteCommand);
}

private void ExecuteDeleteCommand()
{
    // remove the Customer from the ObservableCollection of customers
    // and also delete it from the database, or do anything else you want
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜