Reputation: 86729
I'm relatively new to WPF, and I'm having trouble with what I'm fairly certain is a relatively simple problem.
I have my underlying data object, a Person:
class Person
{
public string Surname {get; set; }
public string Firstname {get; set; }
public List<Address> Addresses {get; }
}
And I wish to display and edit this object in my WPF app. To this end I've created a ViewModel that I bind to in my xaml:
class PersonViewModel
{
public string Fullname {get; }
public ObservableCollection<AddressViewModel> Addresses {get; }
}
This is fine, except when it comes to manipulating my Address collection, where I can't work out what I should be doing:
AddAddress
, RemoveAddress
etc... to my PersonViewModel
class for manipulating my collection with instances of AddressViewModel
AddressViewModel
to my Addresses
observable collectionBoth of the above seem a bit messy - is there a better way of dealing with collections?
Upvotes: 1
Views: 224
Reputation: 1736
I would recommend adding commands in your ViewModel. For example, you would have a AddAddressCommand and a RemoveAddressCommand. you could bind these commands to the View (e.g. you could bind a button to the AddAddressCommand) that will execute a method in your ViewModel that will add to the collection.
public ObservableCollection<AddressViewModel> Addresses { get; set; }
public RelayCommand AddAddressCommand
{
get
{
if (_addAddressCommand == null)
{
_addAddressCommand = new RelayCommand(p => this.AddAddress_Execute());
}
return _addAddressCommand;
}
}
private void AddAddress_Execute()
{
Addresses.Add(new AddressViewModel());
}
(In the above example i'm using RelayCommand, this is a custom Class that implements ICommand, you can read more on this RelayCommand here
Also a side note: I wouldn't create an AddressViewModel I would Just have an AddressModel that implements INotifyPropertyChanged. There is no need to another address viewmodel unless you have display logic that is not in your model.
Upvotes: 2