Gern Blanston
Gern Blanston

Reputation: 42660

WPF binding to collection and adding new item to collection using MVVM

This is probably a simple question...

I have a window with a listbox of employees and a # of textboxes for displaying or entering data. The listbox of employees is bound to an observable collection in my ViewModel, which is read from a database.

Right now I have a SelectedEmployee property that the textboxes are bound to, so if a user clicks on a existing employee it displays the existing attributes.

Now I want to add a new employee from values entered into the textboxes. My thought was a user would enter the values and then click "Add Employee".

But I'm confused as to what the textboxes would be bound to. I don't have an employee object yet and to display existing employees I have need to bind to the SelectedEmployee.

I thought about changing the work flow where a user needs to click "Add New Employee" enter the data and click "Save" but I think I run into the same issue.

I think I'm missing something obvious or my ViewModel is incorrect to support my work flow.

Any suggestions?

Thanks

Upvotes: 2

Views: 2744

Answers (3)

Ingó Vals
Ingó Vals

Reputation: 4898

Do you wan't by default to jump into the Create new employee state? If you wan't to press some button first here is something that might help.

You could put the Collection into a IEditableCollection let the Employee object implement IEditableObject.

Then the user would press a button wich calls the addnew() method of the IeditableCollection (let's call it IEC) wich would add a new item to the collection wich would be in edit mode.

IEC.CancelNew would remove the object again from the collection IEC.CommitNew would add the object permanently and stop editing it.

You would also have access to EditItem, CommitEdit and CancelEdit to edit a object already present.

This removes the hassle of having to save the object when it still hasn't got the right info on it first and then edit the right info in.

Upvotes: 0

jbe
jbe

Reputation: 7031

You might find the BookLibrary sample application of the WPF Application Framework (WAF) useful. It is very similar to the application you describe but it uses books instead of employees. :-)

Upvotes: 0

ThomasAndersson
ThomasAndersson

Reputation: 1904

I suggest that by clicking "Add Employee" a new employee object is created and assigned to SelectedEmployee.

Now that I think about it, maybe it would be better to create a employee object, add it to your collection and point SelectedEmployee to the newly created object.

Upvotes: 1

Related Questions