Search code examples
wpfuser-interfacemvvmcommandbinding

MVVM - Closing a tab when a record is deleted


I'm not really sure how to do this in the best MVVM way...

Basically, my main app opens up a search window that shows all records in a TabPanel. Then if a record is double clicked a new tab is opened with that record. Now, I'm trying to keep things MVVM, but I can't for the life of me figure out how to close the gui tabitem when a person deletes the record (why keep it open if the record is gone).

The only way I can figure out how to do it now is to pass the instance of the TabItem as a parameter of the DeleteCommand, which to me seems like a big no-no, but I can't for the life of me figure out how to accomplish this.


Solution

  • If you were going to do this in the true MVVM sense, then double-clicking a record would, behind the scenes, add a record to a collection of records. That record collection is the datasource for the tabs in your control. Simply removing that item from the list (usually an ObservableCollection<T>) would result in the UI updating and the tab being removed.

    Which approach are you currently using to show the tab?


    Edit (in response to comment):

    That is not "true" MVVM. It doesn't matter if the tabs can be more than just records. You should create View Models which abstract those details, then just put your view model instances (RecordViewModel, ReportViewModel, etc) in an observable collection and bind to that. Use datatemplates to render the correct views for each tab's content based on the type of view model the current tab is being bound to.