ObservableCollection in ViewModel, list in model

I am struggling to find a solution to the problem of keeping two lists.

I am using MVVM

but do not want my model to use ObservableCollection

. I find it best to encapsulate and let me use different views / templates (like console). Instead of setting up my structure like this:

public class MainWindow {
  // handled in XAML file, no code in the .cs file
}

public abstract class ViewModelBase : INotifyPropertyChanged {
  // handles typical functions of a viewmodel base class
}

public class MainWindowViewModel : ViewModelBaseClass {
  public ObservableCollection<Account> accounts { get; private set; }
}

public class Administrator {
  public List<Account> accounts { get; set; }

  public void AddAccount(string username, string password) {
    // blah blah
  }
}

      

I would like to avoid having two different collections / lists in the above case. I want only the model to process the data, and be ViewModel

responsible for the logic of its visualization.

+3


source to share


1 answer


what you can do is use an ICollectionView in your viewmodel to show the model data.

public class MainWindowViewModel : ViewModelBaseClass {
 public ICollectionView accounts { get; private set; }
 private Administrator _admin;

  //ctor
  public MainWindowViewModel()
  {
     _admin = new Administrator();
     this.accounts  = CollectionViewSource.GetDefaultView(this._admin.accounts);
  }

  //subscribe to your model changes and call Refresh
  this.accounts.Refresh();

      



XAML

  <ListBox ItemsSource="{Binding accounts}" />

      

+5


source







All Articles