views:

41

answers:

1

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:

  • Should I add methods AddAddress, RemoveAddress etc... to my PersonViewModel class for manipulating my collection with instances of AddressViewModel
  • Should I just add instances of AddressViewModel to my Addresses observable collection

Both of the above seem a bit messy - is there a better way of dealing with collections?

+2  A: 

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.

Eli Perpinyal
You can replace your if+assignment with a ??-operator.
Henrik
aah cool, thanks.
Eli Perpinyal
You're also either going to need to add an Address to Person.Addresses in AddAddress_Execute to go with the new AddressVM or do some synchronization of the collections later, like on a Save operation.
John Bowen