View only properties (for example: IsSelected) and models in MVVM

Consider a WPF application that is written using MVVM. The application should display a list of employees (FirstName, LastName, Title), and you can select several to delete.

The model in this case will be " Employee ", and it implements INotifyPropertyChanged .

The view will have an " EmployeeListView " that will implement XAML to display a collection of employees.

The ViewModel will be an " EmployeeListViewModel " in which an ObservableCollection will be displayed, which can be bound to an EmployeeListView .

My question is: where should the IsSelected property be ?

  • In the model? (I do not like this idea, since the model now exposes a property that is required only for the presentation and has nothing to do with the actual domain object, also this property would be useless if I implemented the view in different ways and did not allow the removal of several employees at the same time).
  • In EmployeeListViewModel "as a separate collection of dictionaries that will track whether an employee is selected or not? (Or even just a HashSet containing all the selected employees). I donโ€™t like this, because the binding in the view is no longer direct.
  • Deploy a separate EmployeeViewModel that wraps the Employee object and provides the IsSelected property. EmployeeListViewModel then exposes its collection as an ObservableCollection. I like this solution best, but I always thought that there is one ViewModel per view, in which case I have 2 view models for my view. Is this a deviation from the MVVM pattern or is this a typical way to implement MVVM? (links?)
+6
source share
1 answer

Create a reusable Generic SelectableItem element that wraps each element in an EmployeeList:

A simple example:

public class SelectableItem<T>: INotifyPropertyChanged { public bool IsSelected {get;set;} //PropertyChanged(), etc public T Value {get;set;} } 

then in ViewModel:

 public ObservableCollection<SelectableItem<Employee>> Employees {get;set;} 

and in view:

 <DataTemplate> <CheckBox IsChecked="{Binding IsSelected}" Content="{Value.FullName}"/> </DataTemplate> 

Then you can get all the selected employees, simply:

 var selectedemployees = Employees.Where(x => x.IsSelected).Select(x => x.Value); 
+6
source

Source: https://habr.com/ru/post/951527/


All Articles