CollectionViews in MVVM

Typically, to invoke a collection view of a control, I call the following:

            CollectionView cv = (CollectionView)CollectionViewSource.GetDefaultView(list.ItemsSource);

This is usually done in the code behind the xaml file.

However, in MVVM, the ViewModel should not be aware of the existence of a view. How to get a CollectionView of a control if I want to do this using MVVM?

+3
source share
4 answers

You can get CollectionView in ViewModel

1- You have a data source for your list, and you associate the source of the list item with this famous data source.

2. Suppose the DataSource is a DataTable named dt.

 CollectionView cv = (CollectionView)CollectionViewSource.GetDefaultView(dt); 

 this will give you the CollectionView in ViewModel
+1
source

you need to define ItemsSource as a property in ViewModel e.g.

public CollectionView _sourceForList;
public CollectionView SourceForList
        {
            get
            {
                return _sourceForList;
            }
            set
            {
                _sourceForList = value;
            }
        }

then in XAML you can bind this property to a list

<ListBox Margin="9,30,9,0" 
         Name="listBox1" ItemsSource="{Binding SourceForList}" }/>

        CollectionView cv = (CollectionView)CollectionViewSource.GetDefaultView(SourceForList);

,

+1

Get CollectionView in code for xaml (View) file. The MVVM pattern is not related to code removal. It's about sharing problems and verifiability.

The BookLibrary WPF Application Framework (WAF) example shows how to work with CollectionView for filtering in an MVVM application.

0
source

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


All Articles