I have two screens:
- A screen with a list of items, where every item in the list has "Show Details" and "Update buttons"
- An item details screen. The "Show Details" button navigates to item details screen.
When clicking the "Update" button, it needs to take a decision based on item state and then navigate to either to item update screen or ask user for some confirmation before proceeding.
The item details screen has same "Update" button which has same logic.
The issue I have is how to implement the view-models in a clean way such that the update logic is not duplicated.
First, I created the view-models for the screens:
class ItemListViewModel
{
public ObservableCollection<ItemViewModel> Items { get; }
}
class ItemDetailsViewModel
{
// How does this calls ItemViewModel:UpdateCommand ?
public ICommand UpdateCommand { get; }
}
class ItemViewModel
{
public ICommand ShowDetailsCommand { get; }
public ICommand UpdateCommand { get; }
}
For sharing the UpdateCommand, I see the following options:
Have ItemDetailsViewModel create and keep an instance of ItemViewModel:
class ItemDetailsViewModel { ItemViewModel _itemViewModel; public ICommand UpdateCommand => _itemViewModel.UpdateCommand; }
Have ItemDetailsViewModel derive from ItemViewModel:
class ItemDetailsViewModel : ItemViewModel { }
Use a service which implements the update logic, and have both ItemViewModel and ItemDetailsViewModel call it
interface IItemService { void Update(); }
Note that part of the update logic is navigation. I have an IINavigationService which is injected in view-models. I'd have to pass it to the IItemService if I choose to use it.
I don't know which one is the best and why. Here's some of the concerns I have:
- Option #2: seems weird to derive from ItemViewModel.
- Options #3: using the IItemsService service seems appealing, but how to differentiate this service from another items service which is actually saving to storage? Just look at the service and its "Update" method you'd not think it just for navigation logic.
I'd appreciate some advice and reasoning.
The articles\books I could find on MVVM are too simple and don't talk about more complicated scenarios.