I’m learning .NET and WPF while building a small todo list like application.
I’m trying to understand how the ICollectionView interface and CollectionViewSource can be used with MVVM pattern, without breaking it. From what I’ve read they are WPF types, and using them inside the ViewModel strongly couples the View and the ViewModel together.
My application is mostly a datagrid with some buttons that contain commands. The command inside the ViewModel calls a method that assigns a result and moves to the next row by using CollectionViewSource.GetDefaultView(Object).MoveCurrentToNext()
ViewModel
public RelayCommand TestPassedCommand => new RelayCommand(execute => TestPassed(), canExecute => SelectedItem != null);
private void TestPassed()
{
if(_selectedItem != null)
{
_selectedItem.Result = ResultEnum.passed;
}
ICollectionView view = CollectionViewSource.GetDefaultView(HardwareTests);
view.MoveCurrentToNext();
}
What I’ve tried
I removed part of the code that calls the method MoveCurrentToNext()
and added a EventHandler in the code-behind (which also breaks MVVM). The event handler gets executed when the button is clicked, before the command above, although it still works, I don’t like this approach.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void MarkTestPassed(object sender, RoutedEventArgs e)
{
if(DataGrid.SelectedItem != null)
{
ICollectionView view = CollectionViewSource.GetDefaultView(DataGrid.ItemsSource);
view.MoveCurrentToNext();
}
}
}